Skip to content

Instantly share code, notes, and snippets.

@jrmadsen67
Last active December 11, 2015 14:59
Show Gist options
  • Save jrmadsen67/4618291 to your computer and use it in GitHub Desktop.
Save jrmadsen67/4618291 to your computer and use it in GitHub Desktop.
jquery function to move focus to next element of group when max length hit. for use with phone numbers, dates, etc
// assumes you set tabIndex="0" ... last element in group
// set all elements in group with same class
// set each element with max length
// obviously, "phones" is not generic, easy to switch. Code I just wrote for something quick; will fix that later
$('.phone').keyup(function(){
jumpNext($(this), $(this).val())
});
function jumpNext(elem,value){
if (value.length == elem.attr('maxLength')){
var next = elem.attr('tabIndex');
var phones = $('.phone');
if (next < phones.length){
phones.eq( phones.index(elem)+ 1 ).focus();
}
}
}
<div class="control-group">
<label class="control-label">Phone: <span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="phone1" tabindex="0" name="phone1" class="span2 phone" maxlength="3"/>
&nbsp;
<input type="text" id="phone2" tabindex="1" name="phone2" class="span2 phone" maxlength="3"/>
&nbsp;
<input type="text" id="phone3" tabindex="2" name="phone3" class="span2 phone" maxlength="4"/>
&nbsp;Ext:&nbsp;
<input type="text" id="ext" tabindex="3" name="ext" class="span2 phone" value=""/>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment