-3

I have the following code to display an error message if someone already has a registered email address:

$output['error'] = __('Email is taken. Is that you? Try to <a href="#" data-template="login">login</a> to this site or 
<a href="#" id="extend_membership_email">extend your membership to this site</a>
<input type="hidden" id="extend_membership_email_value" value="'.$input_value.'">','userpro');

I then have the following JS to check this:

$( "#extend_membership_email" ).on('click', 'a', function(e) {
    e.preventDefault();
    alert("it is in here");
    var email_member = $('#extend_membership_email_value').val();
    alert(email_member);
});
user1048676
  • 9,756
  • 26
  • 83
  • 120
  • 1
    And your question is....? Also, I suspect the answer is *"use event delegation"* – Phil Apr 21 '15 at 01:35
  • possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) ~ see **Option 3** in the accepted answer – Phil Apr 21 '15 at 01:37
  • 1
    @Phil I thought I was using event delegation but it's not doing it. – user1048676 Apr 21 '15 at 01:37
  • 1
    It doesn't count if the outer element (in your case `#extend_membership_email`) is also dynamically added. You need to go up to an element that already exists like `document`. As an example, `$(document).on('click', '#extend_membership_email', function...` – Phil Apr 21 '15 at 01:39
  • @Phil That was very help and also the answer. Thanks for pointing it out. I didn't realize it wouldn't recognize new elements. – user1048676 Apr 21 '15 at 01:42

2 Answers2

3

Try this:

$(document).on('click', '#extend_membership_email a', function(e) {
    e.preventDefault();
    alert("it is in here");
    var email_member = $('#extend_membership_email_value').val();
    alert(email_member);
});

You need to hook the click event at document and in the second parameter you should set the target's selector (I think you want to listen to the event from an "a" inside "#extend_membership_email".

0

If you are adding new elements, it is not working because it is when $(document).ready(). It gets the HTML elements / DOM from when the page loads.

Try adding it to the HTML file (or whatever you're using) and the hiding it with

  • CSS: display: none / height: 0; overflow: hidden
  • JS: $(object).hide()

and when you want it to

  • Show: $(object).show()
  • FadeIn: $(object).fadeIn('slow')
David Sevilla
  • 97
  • 3
  • 9