Reputation: 2386
I'm dynamically adding 4 text boxes to a div tag. Purpose is to getting IP address. like below,
<input type="text" id='ip1' />
<input type="text" id='ip2' />
<input type="text" id='ip3' />
<input type="text" id='ip4' />
What I'm doing is,
On keyup event, I'm checking it's length, so if it's '3' I have to focus on next textbox. Hope you understand what I'm trying to do.
Jquery Code:
$(document).on('keyup','#ip1', function(e){
if($(this).val().length>=3)
$("#ip3").focus();
});
in above code if the first box length reached 3 digit it suppose to focus second text box #ip2. But it doesn't work, since I've added these fields dynamically. So, my question is,
How to focus on a text field which is generated dynamically??
Upvotes: 0
Views: 87
Reputation: 172
You can also add an extra attribute to the text fields, so you have to define only one jQuery event to do all the work:
<input type="text" id='ip1' next="ip2" />
<input type="text" id='ip2' next="ip3" />
<input type="text" id='ip3' next="ip4" />
<input type="text" id='ip4' next="-" />
JS:
$(document).on('keyup','input', function(e){
if($(this).val().length>=3 && $(this).attr('next') != '-' )
$('#'+$(this).attr('next')).focus();
});
Upvotes: 1
Reputation: 4784
you can bind 'keyup' for individual fields when they are dynamically added as
$("#ip3").keyup(function(){ $('#ip4').focus(); });
Upvotes: 0
Reputation: 148120
You can trying to bind the on event instead of focus.
Change
$(doucment).on(focus,'#ip2');
to
$('#ip2').focus();
Instead of hard coding the event binding and focus code you can make it generic.
$(document).on('keyup','[id^=ip]', function(e){
if($(this).val().length>=3)
$(this).next().focus();
});
Upvotes: 2