简体   繁体   中英

Select previous input with jQuery

How can I go back to the previous input when hitting backspace on an 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 will not fire if the element already has empty value because there's no value change.

A keyup check for backspace press should suffice. Assuming the input elements are always direct siblings as in your 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();
    }
});

Fiddle

I've added a propertychange listener as fallback for old IE, but you can remove it if you don't feel like using this ugly hack to support old IE. Also I've swapped .select() by .focus() so that it doesn't select the entire field upon focusing, but that is up to you too. =]

The e.which === 8 check is so that it only moves to the previous field by pressing the backspace key, but in case you'd like to move to the previous input even if the user erases the field value through other means (eg delete key or cut/delete context menu) you can remove the e.which === 8 too, though that wouldn't make much sense UX-wise imho.

try this

        $('input').bind('input, keydown', function (e) {
           if (this.value.length >= $(this).attr('maxlength')) {
              $(this).next().select();
           }

           if (this.value.length == 0 && e.keyCode == 8) {
              $(this).prev().focus();
           }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM