0

I'm trying to insert a new textfield on a page each time user presses enter.

My code

   $(":text").on("keypress", function(e) {
if (e.keyCode == '13') {
    e.preventDefault()
    $(this).after("<p><input type='text' class='textfield' maxlength='10' value=''/>      <span></span> </p>")
}

    });

A new text field appears when I press enter on orginal text field, but the new one does not react any presses. I assume on-function is similar to live, which should be a fix to this kind of problems. What's wrong?

mjgirl
  • 1,214
  • 7
  • 24
  • 42
  • 1
    You delegate events to exact elements. This means that newly created element are left in cold. You need to make bind keypress to outer container and constrain it to text field. – Tommi Jul 04 '13 at 10:03

2 Answers2

0

You need to do event delegation for the newly added elements.

Use event delegation by using on() function

Ex:

$("#parent").on('keypress', 'textboxselector', function(event) {

----do the things here 
});
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
-1

Please refer below code

        $(".textfield").live("keypress", function (e) {
        if (e.keyCode == '13') {
            e.preventDefault();
            $(this).after("<p><input type='text' class='textfield' maxlength='10' value=''/>      <span></span> </p>")
        }

    });
Chirag Vidani
  • 2,519
  • 18
  • 26