Reputation: 505
I am looking to write a piece of code that will shift/tab the focus of the cursor to the element in the mark-up if the user presses a key in the previous element.
e.g. each time the user enters a character/digit into a input box the focus automatically tabs to the next input box, like in some serial code input forms.
I have previously tried using jquery's .live and .keypress to no avail. Here is the code I have as of writing this.
$('.fmq').keypress(function() {
$(this).next().focus();
}
And here is the markup I have
<input name="serial[1]" type="text" maxlength="1" class="fmq">
<input name="serial[2]" type="text" maxlength="1" class="fmq">
<input name="serial[3]" type="text" maxlength="1" class="fmq">
<input name="serial[4]" type="text" maxlength="1" class="fmq">
<input name="serial[5]" type="text" maxlength="1" class="fmq">
<input name="serial[6]" type="text" maxlength="1" class="fmq">
Hopefully that is enough information to get the point across, if not then please ask me for more.
Appreciate any help that comes and apologies if this has been posted before.
Cheers,
Dan.
Upvotes: 0
Views: 5782
Reputation: 291
JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object)
text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
<option value="1">1</option>
<option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
<option value="1">1</option>
<option value="1">2</option>
</select>
$(function() {
var focusables = $(":focusable");
focusables.keyup(function(e) {
var maxchar = false;
if ($(this).attr("maxchar")) {
if ($(this).val().length >= $(this).attr("maxchar"))
maxchar = true;
}
if (e.keyCode == 13 || maxchar) {
var current = focusables.index(this),
next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
next.focus();
}
});
});
Upvotes: 0
Reputation: 14330
You haven't closed your call to keypress
:
$('.fmq').keypress(function() {
$(this).next().focus();
});
That works for me.
Upvotes: 2