如果变为空,键盘退格键上的jQuery将移至上一个输入字段

Dav*_*vid 3 css jquery focus input backspace

我有这个jQuery脚本:

$(document).ready(function() {
    //Focus the first field on page load
    $(':input:enabled:visible:first').focus();
    //Clear all fields on page load
    $(':input').each(function() {
        this.value = "";
    });
});
//Clear field on focus
$('input').focus(function() {
    this.value = "";
});
//Allow only alphabetical characters in the fields
$(':input').bind("keypress", function(event) {
    if (event.charCode != 0) {
        var regex = new RegExp("^[a-zA-Z]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
        $(this).next('input').focus();
    }
});
//Enumerate submit click on [ENTER]-keypress
$(':input').keypress(function(e) {
    if (e.which == 13) {
        jQuery(this).blur();
        jQuery('#submit').click();
    }
});
//Submit form
$('#submit').click(function() {
    //Show loading image while script is running
    $("#response").html("<img src='../images/loader.gif'>");

    //POST fields as array
    function serealizeInputs(input) {
        var array = [];
        input.each(function() {
            array.push($(this).val())
        });
        return array;
    }

    var letters = serealizeInputs($('.letters'));

    $.post('loadwords.php', {
        letters: letters
    }, function(data) {
        //Show the resonse from loadwords.php
        $("#response").html(data);
    });
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/8S2x3/1/

我想稍微优化一下,但我不知道如何.

因为我还在学习,所以大部分代码都是复制粘贴修改

我的问题:如何将焦点移到Backspace按键上的前一个文本字段?如果您输入错误,我希望能够删除该字符,但如果再次按退格键,则将焦点移至上一个输入字段.所以基本上如果输入=''和按下退格键,移动到前一个字段.如果输入有值,并且按下了退格键,则表现正常(擦除字符)

另外我想知道如果字段中有值,如何添加css类,如果它是空的,则添加另一个css类.

Alf*_*ono 6

尝试:

$(':input').keydown(function(e) {
    if ((e.which == 8 || e.which == 46) && $(this).val() =='') {
        $(this).prev('input').focus();
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴