简体   繁体   中英

Jquery: Keyup event is not fired, on dynamically added input controls

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?

对于动态创建的元素,使用委托事件

$('body').on('keyup', 'input[type=text]' function (e) {

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) {

    });
}

Try the following:

jQuery(document).on('keyup','input[type = text]',function(){
    //execute your code, when dynamically added content is keyupped
});
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.

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM