Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Try this

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

//enter code here

});

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top