leofontes leofontes - 6 months ago 25
HTML Question

Access keyup event on input element generated by code

On my project, I generate div elements that contain input fields with the request response data from my database given the search parameters. I need to be able to use a keyup event on it to do some extra work, however the class selector does not work when the input was generated by using append, even though it has the class on inspection.

I created a CodePen that demonstrates it: http://codepen.io/leofontes/pen/PNgabB?editors=1111

HTML

<div class="container" id="container">
<button id="button">Click</button><br>
</div>


CSS

.container {
background-color: #F00;
height: 200px;
width: 200px;
}

.dynamic-input {
margin: 5px;
}


Javascript / jQuery

$(document).ready(function () {
$('#button').click(function() {
for(var i = 0; i < 5; i++) {
$('#container').append('<input type="text" class="dynamic-input">')
}
});


$('.dynamic-input').keyup(function() {
console.log($(this).val());
});
});


The jQuery code works great, I tested it with inputs generated within the $(document).ready function and it did what I intended, I don't understand why it doesn't when it is generated later on.

I also tried having a hidden input with the class already loaded with the HTML but that doesn't work either.

All ideas or suggestions are appreciated, thank you

Answer

You need event delegation for dynamically generated element.

$('#container').on('keyup', '.dynamic-input', function () {
    console.log($(this).val());
});
Comments