This question already has an answer here:
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');
});
});
Since the class is added dynamically, you need to use event delegation to register the event handler
This will attach your event to any input within the
#mainform
element, reducing the scope of having to check the wholedocument
element tree and increasing efficiency.Do event delegation.
http://api.jquery.com/on/
you need to bind event after appending created div, hence move your binding code inside button click event
Use event delegation (As
.conv
being added dynamically)Demo
--->
http://jsfiddle.net/VxTh5/7/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:
We use
#mainform
since it exists at DOM ready. You can also usedocument
, however, it is a very broad click handler.