Reputation: 821
I am new to jquery. I am trying to automatically move to the next field after a user inputs a correct format/pattern (regex value).
Here is what I have so far:
Form:
<form>
<label for="serial_number">Serial Number: </label>
<input type="text" id="serial_number" name="serial_number" placeholder="Serial Number" pattern="[0-9]{5}" maxlength="5" required autofocus />
<input type="text" id="second_entry" name="second_entry" placeholder="second_entry" pattern="[0-9]{5}" maxlength="5" required />
<input type="submit" value="Process" />
</form>
Jquery:
$('.serial_number').keyup(function() {
var inputVal = $(this).val();
var characterReg = /^[0-9]\d{20}$/;
if(characterReg.test(inputVal)) {
$("serial_number").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});
}
});
Any assistance would be greatly appreciated!
Upvotes: 2
Views: 4040
Reputation: 4699
Here you are. Have a look at the code...
jQuery(document).ready(function() {
$('#serial_number').keyup(function() {
var inputVal = $(this).val();
var characterReg = /^\d{5}$/;
if(characterReg.test(inputVal)) {
$("#serial_number").next("input").focus();
}
});
});
For IDs you should use the #
selector. For classes, use .
.
The change
event is not fired until the input loses focus, so you need to do all your checking in the keyup
event.
You can use the next
function to get an element's immediate sibling.
Focus
sets the user's focus to that element, and so puts the cursor in the next input here
Upvotes: 1
Reputation: 56509
There is error in your selector.
$('.serial_number').keyup(function() {
to
$('#serial_number').keyup(function() {
Update: Try the below code:
$('#serial_number').keyup(function () {
var inputVal = $(this).val();
var characterReg = /^[0-9]{5}$/;
if (characterReg.test(inputVal)) {
var inputs = $(this).closest('form').find(':input');
inputs.eq(inputs.index(this) + 1).focus();
}
});
There is no need for .change()
. Check this JSFiddle
Also you need to change your regex
to
var characterReg = /^[0-9]{5}$/;
in the jQuery code because you have maxlength="5"
Upvotes: 5