Search code examples
jquerydynamicelementbindunbind

jQuery: dyanically attach keyup to a dynamically created input


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?


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