0

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

Community
  • 1
  • 1
David
  • 3,612
  • 2
  • 20
  • 33

3 Answers3

3

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.

Community
  • 1
  • 1
SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • Thank you very much. I used an ID because it was convenient in editor. My real code is much different and actually binds to a few different things to get to the keyup. I will accept the answer in 10 minutes, when it allows! – David Mar 03 '13 at 17:05
1

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>
1

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

});