简体   繁体   English

文本输入:将输入限制为数字 (0-9) 和减号 (-)。 没有按预期工作

[英]Text Input: Limit input to numbers (0-9) and the minus sign (-). Not working as expected

I am trying to limit keyboard input in my text field to numbers [0-9] and the minus sign - only (no copy/paste, etc.) and the delete key obviously.我试图将我的文本字段中的键盘输入限制为数字[0-9]和减号-仅(没有复制/粘贴等)和删除键。

The code works for limiting to numbers and the delete key but it doesn't work for the minus sign - part.该代码适用于限制数字和删除键,但不适用于减号-部分。

The user should only be able to enter a minus sign - in front of their number, if they try to enter 1 then - it should not input the - but right now the - part doesn't work at all.用户应该只能输入一个减号-在他们的号码前面,如果他们尝试输入1那么-它不应该输入-但现在-部分根本不起作用。

Fiddle: http://jsfiddle.net/7XLqQ/1/小提琴: http : //jsfiddle.net/7XLqQ/1/

I think this piece of code is the issue but it looks fine.我认为这段代码是问题所在,但看起来不错。 It checks that the text input is blank and if so it input the minus sign - .它检查文本输入是否为空,如果是,则输入减号-

// Only enter the minus sign (-) if the user enters it first
if (unicode == 45 && input.value == "") {
    return true;
}

My full code:我的完整代码:

<input type="text" maxlength="10" id="myInput">

<script>
var input = document.getElementById("myInput");

input.onkeypress = function(e) {
   var unicode = e.keyCode;

    if (unicode == 49 || unicode == 50 || unicode == 51 || unicode == 52 || unicode == 53 || unicode == 54 || unicode == 55 || unicode == 56 || unicode == 57 || unicode == 48) {
        return true;
    } else {
        return false;   
    }

    // Only enter the minus sign (-) if the user enters it first
    if (unicode == 45 && input.value == "") {
        return true;
    }
};
</script>

Order of opperations, you are returning false on the 0-9 before you are ever asking about the minus sign.操作顺序,在您询问减号之前,您会在 0-9 上返回 false。 move the minus sign if block above the 0-9 if block and you are golden将减号 if 块移到 0-9 if 块上方,您就是金子

<input type="text" maxlength="10" id="myInput">

<script>
var input = document.getElementById("myInput");

input.onkeypress = function(e) {
   var unicode = e.keyCode;

    // Only enter the minus sign (-) if the user enters it first
    if (unicode == 45 && input.value == "") {
        return true;
    }

    if (unicode == 49 || unicode == 50 || unicode == 51 || unicode == 52 || unicode == 53 || unicode == 54 || unicode == 55 || unicode == 56 || unicode == 57 || unicode == 48) {
        return true;
    } else {
        return false;   
    }


};
</script>

I'd suggest:我建议:

var input = document.getElementById("myInput");

input.onkeypress = function(e) {
    switch (e.keyCode){
        case 45:
            return this.value.length == 0 ? true : false;
            break;
        case 48:
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
            return true;
            break;
        default:
            return false;
            break;
    }
};

JS Fiddle demo . JS小提琴演示

The reason your original code failed is simply that you'd already returned from the function before the if condition could be assessed.您的原始代码失败的原因很简单,因为您在评估if条件之前已经从函数返回。 In this version if the - key is pressed a ternary returns true if there is no current value (so the - will be the first character), or false if there is already a value (and therefore the - will not be the first character).在这个版本中,如果按下-键,如果没有当前值(因此-将是第一个字符),则三元返回true如果已经有值(因此-将不是第一个字符),则返回false .

keyCode is the wrong property in all browsers except IE. keyCode在除 IE 之外的所有浏览器中都是错误的属性。 You need charCode or which in other browsers.您需要charCode或其他浏览器中的which Using this you'll get character code instead and can use a regular expression to test the typed character.使用它,您将获得字符代码,并且可以使用正则表达式来测试输入的字符。 You also need to allow non-printable keypresses such as delete, backspace and arrow keys in browsers that fire keypress events for such keys.您还需要在浏览器中允许不可打印的按键,例如删除、退格和箭头键,这些keypress会触发此类按键的keypress事件。

Demo: http://jsfiddle.net/7XLqQ/3/演示: http : //jsfiddle.net/7XLqQ/3/

var input = document.getElementById("myInput");

input.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

    // Allow non-printable keys
    if (!charCode || charCode == 8 /* Backspace */ ) {
        return;
    }

    var typedChar = String.fromCharCode(charCode);

    // Allow numeric characters
    if (/\d/.test(typedChar)) {
        return;
    }

    // Allow the minus sign (-) if the user enters it first
    if (typedChar == "-" && this.value == "") {
        return;
    }

    // In all other cases, suppress the event
    return false;
};

There is one case that isn't considered here, which is when the user places the caret at the start of the input and types a minus sign.这里没有考虑一种情况,即用户将插入符号放在输入的开头并键入一个减号。 For that, you'd need to detect the caret position.为此,您需要检测插入符号的位置。 Here's some cross-browser code to detect whether the caret is at the start of the input, adapted from this answer :这是一些跨浏​​览器代码,用于检测插入符号是否位于输入的开头,改编自此答案

function isCaretAtTheStart(el) {
    if (typeof el.selectionEnd == "number") {
        // Modern browsers
        return el.selectionEnd == 0;
    } else if (document.selection) {
        // IE < 9
        var selRange = document.selection.createRange();
        if (selRange && selRange.parentElement() == el) {
            // Create a working TextRange that lives only in the input
            var range = el.createTextRange();
            range.moveToBookmark(selRange.getBookmark());
            return range.moveEnd("character", -el.value.length) == 0;
        }
    }
    return false;
}

Here's a revised demo: http://jsfiddle.net/7XLqQ/5/这是修改后的演示: http : //jsfiddle.net/7XLqQ/5/

Finally, my favourite resource on JavaScript key events, which will tell you everything you need to know: http://unixpapa.com/js/key.html最后,我最喜欢的 JavaScript 关键事件资源,它会告诉你你需要知道的一切: http : //unixpapa.com/js/key.html

I'd suggest:我建议:

$(".class_name").keypress(function (e) {
   if (e.which != 8 && e.which != 0 && e.which != 45 && (e.which < 48 || e.which > 57)) {
      return false;
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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