JaiSat
JaiSat

Reputation: 2386

I couldn't focus() on a text field upon keyup event

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

Answers (3)

JaGo
JaGo

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();
});

http://jsfiddle.net/gp2Mk/

Upvotes: 1

Yogesh
Yogesh

Reputation: 4784

you can bind 'keyup' for individual fields when they are dynamically added as

$("#ip3").keyup(function(){ $('#ip4').focus(); });

Upvotes: 0

Adil
Adil

Reputation: 148120

You can trying to bind the on event instead of focus.

Live Demo

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

Related Questions