javascript - Select previous input with jQuery -
how can go previous input when hitting backspace on empty input?
$('input').bind('input', function() { if (this.value.length >= $(this).attr('maxlength')) { $(this).next().select(); } if (this.value.length == 0) { $(this).prev().select(); } });
jsfiddle: http://jsfiddle.net/ewykx/
the input
event not fire if element has empty value because there's no value change.
a keyup
check backspace press should suffice. assuming input elements direct siblings in example:
$('input').on('input propertychange', function() { if (this.value.length >= this.maxlength) { $(this).next().focus(); } }).keyup(function(e) { if (e.which === 8 && !this.value) { $(this).prev().focus(); } });
i've added propertychange
listener fallback old ie, can remove if don't feel using ugly hack support old ie. i've swapped .select()
.focus()
doesn't select entire field upon focusing, too. =]
the e.which === 8
check moves previous field pressing backspace key, in case you'd move previous input if user erases field value through other means (e.g. delete key or cut/delete context menu) can remove e.which === 8
too, though wouldn't make sense ux-wise imho.
Comments
Post a Comment