3

我有这个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);
    });
});

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

我想优化它一点,但我不知道如何。

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

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

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

4

3 回答 3

6

尝试:

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

小提琴

于 2012-12-20T20:34:22.530 回答
2

试试这个:

$(':input').keydown(function(e)
{
    if($(this).val() =='' && e.which ==8)
    {
        alert("Backspace pressed when input empty");
    }        
});
于 2012-12-20T20:35:22.023 回答
2

这是填充一组四个输入的解决方案,每个输入仅包含一个字符,用于竞赛或登录或像我的一样,以确认会议邀请:

  1. 单击输入时,将选择所有文本。
  2. 输入字符时,光标转到下一个输入。
  3. 删除时,光标移至上一个输入。

带有用于登录或竞赛的代码输入的表单

HTML:

<div class="code">
    <input type="text" name="code1" maxlength="1" />
    <input type="text" name="code2" maxlength="1" />
    <input type="text" name="code3" maxlength="1" />
    <input type="text" name="code4" maxlength="1" />
</div>

jQuery :

$(":input").on("focus",function(e){
    $(this).select();
});
$(":input").on("mouseup",function(e){
    $(this).select();
    return false;
});
$(':input').keyup(function(e) {
    if (e.which == 8 || e.which == 46) {
        $(this).prev('input').focus();
    }
    else {
        $(this).next('input').focus();
    }
});
于 2017-03-19T20:06:07.353 回答