简体   繁体   中英

jQuery Not Binding to Newly-Created <input> Element

This is what I have:

<script language="javascript">
$('#click').one('click', function () {
   var html = '<input type="text" class="input-mini" id="new-input" />';
   $(this).parent().append(html);
});
$('#new-input').on('keyup', function (e) {
   alert('A key was pressed');
   if (e.keyCode == 13) {
      alert('Enter key pressed');
   }
});
</script>

At the recommendation of other SO answers , I found that I should use on() to bind dynamically created elements. What I want to happen is for an AJAX call to occur after the user presses the Enter key inside the <input> with ID new-input . However, nothing happens when any key is pressed at all.

What do I need to do in order to bind the keyup method to the newly-appended <input> element?

Thanks

Read the documentation

.on() does not always bind dynamically-created elements; it only does that if you pass a selector to listen inside of:

$('some container').on('click', '.new-input', function() { ... });

Also, IDs must be unique; you should use classes.

At the time that the keyup binding is created, there won't be a matching element on the dom - try moving the second binding inside the callback for the first:

<script language="javascript">
    $('#click').one('click', function () {
       var html = $('<input type="text" class="input-mini" />');

       html.on('keyup', function (e) {
           alert('A key was pressed');
           if (e.keyCode == 13) {
               alert('Enter key pressed');
           }
        });

       $(this).parent().append(html);
    });
</script>

jsFiddle Link : http://jsfiddle.net/qTd9c/

$('#click').one('click', function () {
    var html = '<input type="text" class="input-mini" id="new-input" />';
    $(this).parent().append(html);

    $('#new-input').on('keyup', function (e) {
        alert('A key was pressed');
        if (e.keyCode == 13) {
            alert('Enter key pressed');
        }
    });

});

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