2

I am generating HTML elements using javascript. I applied the same class to all elements. I have a function that will execute when that class experiences the keyup event.

The problem is that my function is not recognizing the elements that javascript created.

See the example here --> jsFiddle

HTML

<p>Type in the box below, an alert will appear</p>
   <input type='text' id='x' size='30' class='conv'/>
   <br/><br/>

   <button id='btn'>Now Click Me</button><br/><br/>

   <div id='mainform'></div>

jQuery

$(document).ready(function() {
    $('button').click(function() {
      var a =  "<p>The boxes below have the same class, thus they should show the alert when you type</p><input type='text' size='30' class='conv' id='a0'/><br/>";
      var b = "<input type='text' size='30' class='conv' id='a1'/><br/>";
      $('#mainform').append(a + b);       
    });

    $('.conv').keyup(function() {
       alert('it works'); 
    });

});
Sanya
  • 1,180
  • 4
  • 18
  • 39

5 Answers5

4

Use event delegation (As .conv being added dynamically)

$('#mainform').on('keyup','.conv',function() {
     alert('it works'); 
});

Demo ---> http://jsfiddle.net/VxTh5/7/

Mohammad Adil
  • 43,337
  • 17
  • 86
  • 109
3

Since the class is added dynamically, you need to use event delegation to register the event handler

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#mainform').on('keyup', '.conv', function(event) {
    event.preventDefault();
    alert('it works');
});

This will attach your event to any input within the #mainform element, reducing the scope of having to check the whole document element tree and increasing efficiency.

palaѕн
  • 64,836
  • 15
  • 100
  • 121
2

Do event delegation.

$(document).on('keyup' ,'.conv',function() {
       alert('it works'); 
    });

http://api.jquery.com/on/

Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
2

The reason it's not working is because your element doesn't exist at DOM ready, therefore when your handler is called, it doesn't find these elements. Event delegation binds the click event to an element that exists:

$("#mainform").on('keyup', '.conv', (function() {
   alert('it works'); 
});

We use #mainform since it exists at DOM ready. You can also use document, however, it is a very broad click handler.

tymeJV
  • 99,730
  • 13
  • 150
  • 152
1

you need to bind event after appending created div, hence move your binding code inside button click event

$(document).ready(function() {
    $('button').click(function() {
      var a =  "<p>The boxes below have the same class, thus they should show the alert when you type</p><input type='text' size='30' class='conv' id='a0'/><br/>";
      var b = "<input type='text' size='30' class='conv' id='a1'/><br/>";
      $('#mainform').append(a + b);
       $('.conv').keyup(function() {
          alert('it works'); 
       });

    });
});
Bhushan Kawadkar
  • 27,451
  • 5
  • 33
  • 55