Reputation: 9959
The following
$('input[type = text]').on('keyup', function (e) {
});
works great on static created control
<input id="txtSearch" type="text" class="col-md-12 col-sm-12 col-xs-12 col-lg-12">
but does not fire, on controls created dynamically and rendered as
<input type="text" class="form-control" id="idName" name="textBox">
via a mixture of ajax json response and html.
jQuery.each(response.controls, function (index, item) {
var input = jQuery("<div class='form-group'><input type='text' class='form-control' id='" + item.id + "' name='textBox'></div>");
jQuery('#fields').append(input);
});
What am i doing wrong here?
Upvotes: 1
Views: 1841
Reputation: 7980
Since your <div class='form-group'><input type='text' class='form-control' id='" + item.id + "' name='textBox'></div>
is a dynamic element.
You need to bind the key up event after you have appended it. For example.
jQuery.each(response.controls, function (index, item) {
var input = jQuery("<div class='form-group'><input type='text' class='form-control' id='" + item.id + "' name='textBox'></div>");
jQuery('#fields').append(input);
inputevent();
});
function inputevent() {
$('input[type = text]').off('keyup').on('keyup', function (e) {
});
}
Or you can bind your keyup event as delegate by referencing to your wrapper element i.e. #fields
in your case. So, the code might look as follows:
$('#fields').on('keyup', 'input[type=text]', function (e) {
});
Upvotes: 2
Reputation: 1509
For the element added dynamically to DOM, you need to bind the event to them using on()
$(document).on("keyup",'input[type=text]', function(){
//do your work
});
Upvotes: 0
Reputation: 68933
For dynamically created element use delegated event:
$('body').on('keyup', 'input[type=text]' function (e) {
Upvotes: 2
Reputation: 19
catchKeyup(id) {
// code here...
}
jQuery.each(response.controls, function (index, item) {
var input = jQuery("<div class='form-group'><input type='text' class='form-control' id='" + item.id + "' onkeyup='catchKeyup(" + item.id +")' name='textBox'></div>");
jQuery('#fields').append(input);
});
If you are creating input by any response of request. Maybe you should use general function for keyup. In this way you could use input keyup function.
Upvotes: 0
Reputation: 374
Try the following:
jQuery(document).on('keyup','input[type = text]',function(){
//execute your code, when dynamically added content is keyupped
});
Upvotes: 0