如何在javascript中启用箭头键

时间:2014-08-07 10:37:35

标签: javascript jquery

在我的应用程序中,我为文本字段(用户名)编写了java脚本验证。因此,它只允许字母,空格,后空格和箭头在文本字段中移动上一个和下一个字母。我的代码在mozila firefox中运行正常,但是Chrome和IE不允许使用箭头键。

我的代码是这样的..

<input class="form-control input-lg" onkeypress="return isCharacterKey(event)" onkeyup="capitalize(this)" id="firstNameSpaceCapital"/>

//This function allows space,backspace,alphabets and arrow keys
function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    return false;
}

//This method is used to capitalize the first letter in the text field
function capitalize(obj) {
    obj.value = obj.value.charAt(0).toUpperCase() + obj.value.slice(1);
}

//This method is used to capitalize the first letter after space
$('#firstNameSpaceCapital').on('keyup', function () {
    $(this).val(function (i, val) {
        return val.replace(/(\s)(\S)/g, function ($0, $1, $2) {
            return $1 + $2.toUpperCase();
        });
    });
});

3 个答案:

答案 0 :(得分:1)

我这样解决你的问题:

关于大写的通知只需要css(至少你提出的情况)

FIDDLE

HTML

<input class="form-control input-lg" id="firstNameSpaceCapital" />

CSS

.input-lg {text-transform:capitalize;}

JS

$('#firstNameSpaceCapital').on('keypress', isCharacterKey);

function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    evt.preventDefault();
}
祝你好运!

答案 1 :(得分:0)

return isCharacterKey(event)

event未定义,请改用this

return isCharacterKey(this)

答案 2 :(得分:0)

我认为抓住键盘事件是一个坏主意。 &#39;因为用户可以使用鼠标粘贴一些文本。因此,我建议您使用oninput事件