jQuery Mobile focus next input on keypress

user738175 picture user738175 · May 4, 2011 · Viewed 14.9k times · Source

I have a jquery mobile site with a html form consisting of 4 pin entry input boxes. I want the user to be able to enter a pin in each input field without having to press the iphone keyboards "next" button. I have tried the following and although it appears to set the focus to the second input and insert the value, the keyboard disappears so the user still has to activate the required input with a tap event.

$('#txtPin1').keypress(function() {
        $('#txtPin1').bind('change', function(){  
            $("#txtPin1").val($("#txtPin1").val()); 
        });
        $("#txtPin2").focus();
        $("#txtPin2").val('pin2');
});

Is there a different event that I should be assigning to $("#txtPin2")?

I have tried to implement http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/ this also, but I found that it worked for android and not for iphone.

Any help is greatly appreciate it.

Answer

Phill Pafford picture Phill Pafford · May 5, 2011

Live Example: http://jsfiddle.net/Q3Ap8/22/

JS:

$('.txtPin').keypress(function() {
    var value = $(this).val();

    // Let's say it's a four digit pin number
    // Value starts at zero
    if(value.length >= 3) {
        var inputs = $(this).closest('form').find(':input');
        inputs.eq( inputs.index(this)+ 1 ).focus();
    }
});

HTML:

<div data-role="page" data-theme="b" id="jqm-home">
    <div data-role="content">
        <form id="autoTab">
            <label for="name">Text Pin #1:</label>
            <input type="text" name="txtPin1" id="txtPin1" value="" class="txtPin" placeholder="Please enter Pin #1"/>

            <br />
            <label for="name">Text Pin #2:</label>
            <input type="text" name="txtPin2" id="txtPin2" value="" class="txtPin" placeholder="Please enter Pin #2"/>

            <br />
            <label for="name">Text Pin #3:</label>
            <input type="text" name="txtPin3" id="txtPin3" value="" class="txtPin" placeholder="Please enter Pin #3"/>

            <br />
            <label for="name">Text Pin #4:</label>
            <input type="text" name="txtPin4" id="txtPin4" value="" class="txtPin" placeholder="Please enter Pin #4" maxlength="4"/>
        </form>
    </div>
</div>