jQuery: dyanically attach keyup to a dynamically created input

2.7k views Asked by At

So I have this scenario

When I load the form I originally have an input of type text.

That input has the "keyup" event attached to it, if the user has entered more than 5 characters a new input text is injected after the input element and also unbind the keyup event from the current element.

HTML:

<form>
    <input id="input1" type="text" class="email-input" />
</form>

JQUERY:

$('.email-input').on({

    keyup: function() {
        if (this.value.length > 5)
        {
            var newInput = $("<input type='text' class='email-input' />");
            $('form').append(newInput);

            $(this).unbind('keyup');
        }
    }

});

I want the newly created elements to have the same functionality as the originally created element. How do I achieve that?

3

There are 3 answers

0
A. Wolff On BEST ANSWER

Delegate event to the FORM:

DEMO

$('form').on({    
    keyup: function() {
        if($(this).data('unbind')) return;
        if (this.value.length > 5)
        {
            var newInput = $("<input type='text' class='email-input' />");
            $('form').append(newInput);
            //used to filter event, you cannot unbind here delegated event just for specific element
            $(this).data('unbind',true);
        }
    }

},'.email-input');
1
aim88 On

Try this

$('.email-input').live('keyup', function() {

//enter code here

});

0
Louis XIV On

You can do it with this syntax:

$(document).on('keyup', '.email-input', function() {
    // code
});

example here: http://jsfiddle.net/922Yj/

Or delegate it on the form (instead of the document), like a previous answer said.