Asif
Asif

Reputation: 766

jQuery onChange() get another field focused

Please visit this fiddle first: http://jsfiddle.net/7Prys/

What I want to get when user inputs the first fields (user can input only one string per field) the second one get focused in automatically, and this continues until the fourth input field. Is there a quick jQuery for it? And also when I delete the code the previous one will be focused one by one on pressing the backspace key.

Here is the html:

<input type="text" maxlength="1" class="small" />
<input type="text" maxlength="1" class="small" />
<input type="text" maxlength="1" class="small" />
<input type="text" maxlength="1" class="small" />

and jQuery:

$(".small").onchange(function () {
    $(this).next().find(".small").focusIn();
});

Upvotes: 0

Views: 2735

Answers (6)

Mooseman
Mooseman

Reputation: 18891

Here you go:

$(".small").on('keyup', function (e) {
    if(e.keyCode == 8){ /* backspace */
        $(this).prev('.small').focus();
    }else{
        $(this).next('.small').focus();
    }
});

Fiddle: http://jsfiddle.net/7Prys/10/
This will go to the next input when any key other than backspace is pressed, and go to the previous input when backspace is pressed. Note that you can add || e.keyCode == 46 the the if statement if you want to recognize the Delete key.


There is no such thing as .onChange or .focusIn. .on can be used for the keyup event as in my example. Also, .find().next('.small') should just be .next('.small').

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191829

There are a variety of issues here.

onchange should be change, but that will only be triggered when the input loses focus, which doesn't work so well. I suggest using .keyup.

$(this).next() is the input element, so $(this).next().find(".small") won't find anything. You could use $(this).next(".small"), but $(this).next() is sufficient.

http://jsfiddle.net/ExplosionPIlls/7Prys/6/

EDIT: you can check e.which == 8 to determine if the backspace was pressed and then use .prev instead.

http://jsfiddle.net/ExplosionPIlls/7Prys/11/

Upvotes: 3

Collin Henderson
Collin Henderson

Reputation: 1154

This worked for me:

$(".small").keyup(function (e) {
    if(e.keyCode == 46 || e.keyCode == 8){
        $(this).prev('.small').focus();
    }
    else {
      $(this).next('.small').focus();
    }
});

Fiddle: http://jsfiddle.net/5Sv2f/

Upvotes: 6

user
user

Reputation: 545

it's .change() not .onChange()

http://api.jquery.com/change/

Upvotes: 0

j08691
j08691

Reputation: 208040

Try:

$(".small").keyup(function () {
    $(this).next().focus();
});

jsFiddle example

A few notes. In jQuery you use .change(), not .onchange(). Second, .find() searches through descendant elements, so it your example it would never find the right element since they're siblings.

Upvotes: 3

Naftali
Naftali

Reputation: 146360

There is no such thing as the on change event.

There is a change event you can use.

Upvotes: 2

Related Questions