Thursday, 13 March 2014

Jquery Auto Tabs (Simple And Easy)

You have a form for allowing users to register a product online, and you require the
user to enter a serial number printed on the installation discs. This number is 16 digits
long and separated across four input fields. Ideally, to speed the user along in their data
entry, as each input field is filled up, you’d like to automatically focus the next input
field until they’re finished typing the number:

<fieldset class="autotab">
<legend>Product Serial Number</legend>
<input type="text" maxlength="4" />
<input type="text" maxlength="4" />
<input type="text" maxlength="4" />
<input type="text" maxlength="4" />
</fieldset>



Inside <fieldset class="autotab">, find all the <input> elements. Use
jQuery’s .bind() method to listen for the keydown and keyup events. We exit the bound
function for a handful of keys that we want to ignore, because they aren’t meaningful
for automatically tabbing forward or backward. When an <input> element is full, based
on the maxlength attribute, we .focus() the next <input> element. Conversely, when
using the Backspace key, if an <input> element is made empty, we .focus() the previous
<input> element:


$('fieldset.autotab input').bind('keydown keyup',function(event){
// the keycode for the key evoking the event
var keyCode = event.which;
// we want to ignore the following keys:
// 9 Tab, 16 Shift, 17 Ctrl, 18 Alt, 19 Pause Break, 20 Caps Lock
// 27 Esc, 33 Page Up, 34 Page Down, 35 End, 36 Home
// 37 Left Arrow, 38 Up Arrow, 39 Right Arrow, 40 Down Arrow
// 45 Insert, 46 Forward Delete, 144 Num Lock, 145 Scroll Lock
var ignoreKeyCodes =
',9,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45,46,144,145,';
if ( ignoreKeyCodes.indexOf(',' + keyCode + ',') > −1 ) { return; }
// we want to ignore the backspace on keydown only
// let it do its job, but otherwise don't change focus
if ( keyCode == 8 && event.type == 'keydown' ) { return; }
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
// if backspace key and there are no more characters, go back
if ( keyCode == 8 && currentLength == 0 ) {
$this.prev().focus();
}
// if we've filled up this input, go to the next
if ( currentLength == maximumLength ) {
$this.next().focus();
}
});

LIVE DEMO

No comments:

Post a Comment

Thank your for your comment..your submitted coment will be live after admin approval