Reputation: 1443
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?
Upvotes: 1
Views: 2718
Reputation: 2224
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.
Upvotes: 4
Reputation: 561
Try this
$('.email-input').live('keyup', function() {
//enter code here
});
Upvotes: -1
Reputation: 74420
Delegate event to the FORM:
$('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');
Upvotes: 4