Here is one approach:
// binds to both the 'keyup' and 'paste' events $('input:text').on('keyup paste', function(e) { var that = $(this), // caches the $(this) val = that.val(), // access the value of the current input key = e.which, // determines which key was pressed allowed = [8, 46, 9, 16]; // defines 'allowed' keys (for editing/focusing) // backspace, delete, tab, shift if ($.inArray(key, allowed) == -1) { // if the pressed key is *not* an 'allowed' key if (val.length == 5) { // focuses the next element that.next().focus(); } else if (val.length > 5) { // truncates the string, if greater than 5 characters that.val(val.substring(0, 5)); that.next().focus(); } } });β
JS Fiddle demo .
The advantage of this approach is that instead of masking or manipulating the input line and taking into account multiple boundary cases, you simply help the user by moving the focus to the desired point. And in this case also allows the user to reorient the re-editing of previously entered data.
source share