I have an ASP.NET web forms project that I am trying to implement auto-tabbing in. I’m new to jquery, but I found a code snippet online to do auto-tabbing, and I want to use it to autotab multiple groups of textboxes.
For example:
Textbox1 -> Textbox2 -> Textbox3
Textbox4 -> Textbox5 -> Textbox6
But not:
Textbox3 -> Textbox4
Hope that makes sense. Anyway, I have the following code:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".autotab").keyup(function () {
if ($(this).attr("maxlength") == $(this).val().length) {
var index = $(".autotab").index(this);
var item = $($(".autotab")[++index]);
if (item.length > 0)
item.focus();
}
});
$(".autotab2").keyup(function () {
if ($(this).attr("maxlength") == $(this).val().length) {
var index = $(".autotab2").index(this);
var item = $($(".autotab2")[++index]);
if (item.length > 0)
item.focus();
}
});
});
</script>
<input name="tbOne" type="text" maxlength="3" id="tbOne" class="autotab" />
<input name="tbTwo" type="text" maxlength="3" id="tbTwo" class="autotab" />
<input name="tbThree" type="text" maxlength="4" id="tbThree" class="autotab" />
<input name="tbFour" type="text" maxlength="3" id="tbFour" class="autotab2" />
<input name="tbFive" type="text" maxlength="3" id="tbFive" class="autotab2" />
<input name="tbSix" type="text" maxlength="4" id="tbSix" class="autotab2" />
How can I refactor the copy/pasted code into a single function?
A more general solution, that doesn’t require that you use one class per group:
As a side note, the
$($(".autotab2")[++index])in your code would have been better written as$(".autotab2").eq(index + 1)