I have one payment page where I have three field called sort code each field can have 2 two digit I want to write java script code to validate this field and as user type 2 digit in first field its should jump to next field. how to validate static sort code.
2 Answers
You'll have to create a collection of your inputs, and proceed to the next item in the collection after the second letter is typed.
var $inputs = $('.input-class');
$inputs.on('keyup', function() {
if ($(this).val().length == 2) {
$inputs.eq($inputs.index(this) + 1).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<table>
<tr>
<td>
<input type="text" class="input-class input-1">
</td>
<td>
<input type="text" class="input-class input-2">
</td>
<td>
<input type="text" class="input-class input-3">
</td>
<td>
<input type="text" class="input-class input-4">
</td>
<td>
<input type="text" class="input-class input-5">
</td>
</tr>
</table>
</form>
If you'd like a more fine tuned solution, you can add as a data-attribute the selector of the next input
var $inputs = $('.input-class');
$inputs.on('keyup', function() {
if ($(this).val().length == 2) {
$($(this).data('next')).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<table>
<tr>
<td>
<input type="text" class="input-class input-1" data-next=".input-3">
</td>
<td>
<input type="text" class="input-class input-2" data-next=".input-4">
</td>
<td>
<input type="text" class="input-class input-3" data-next=".input-5">
</td>
<td>
<input type="text" class="input-class input-4" data-next=".input-1">
</td>
<td>
<input type="text" class="input-class input-5" data-next=".input-2">
</td>
</tr>
</table>
</form>
This is just the "go to next" code, no validation is performed.