有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

以下是我仅针对React用户的简单解决方案,我找不到更好的解决方案,所以我自己做了一个。3步骤。

首先,创建一个状态。

const [tagInputVal, setTagInputVal] = useState("");

然后,使用状态作为输入值(value={tagInputVal})并将事件传递给onChange处理程序。

<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>

然后,在onChange处理程序中设置事件的值。

function onChangeTagInput(e) {
    setTagInputVal(e.target.value.replace(/[^\d.]/ig, ""));
}

其他回答

正则表达式和匹配函数可以很好地处理这种情况。例如,我使用下面的代码来验证图上作为坐标的4个输入框。它运行得相当好。

function validateInput() {
   if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
       jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
         alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
         location.reload();
   }
}

如果你可以使用插件,这里有一个我测试过的。除了膏体外,效果很好。

数字输入

这里是一个演示http://jsfiddle.net/152sumxu/2

下面的代码(库内粘贴)

<div id="plugInDemo" class="vMarginLarge">
    <h4>Demo of the plug-in    </h4>
    <div id="demoFields" class="marginSmall">
        <div class="vMarginSmall">
            <div>Any Number</div>
            <div>
                <input type="text" id="anyNumber" />
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    //    Author: Joshua De Leon - File: numericInput.js - Description: Allows only numeric input in an element. - If you happen upon this code, enjoy it, learn from it, and if possible please credit me: www.transtatic.com
    (function(b) {
        var c = { allowFloat: false, allowNegative: false};
        b.fn.numericInput = function(e) {
            var f = b.extend({}, c, e);
            var d = f.allowFloat;
            var g = f.allowNegative;
            this.keypress(function(j) {
                var i = j.which;
                var h = b(this).val();
                if (i>0 && (i<48 || i>57)) {
                    if (d == true && i == 46) {
                        if (g == true && a(this) == 0 && h.charAt(0) == "-") {
                            return false
                        }
                        if (h.match(/[.]/)) {
                            return false
                        }
                    }
                    else {
                        if (g == true && i == 45) {
                            if (h.charAt(0) == "-") {
                                return false
                            }
                            if (a(this) != 0) {
                                return false
                            }
                        }
                        else {
                            if (i == 8) {
                                return true
                            }
                            else {
                                return false
                            }
                        }
                    }
                }
                else {
                    if (i>0 && (i >= 48 && i <= 57)) {
                        if (g == true && h.charAt(0) == "-" && a(this) == 0) {
                            return false
                        }
                    }
                }
            });
            return this
        };
        function a(d) {
            if (d.selectionStart) {
                return d.selectionStart
            }
            else {
                if (document.selection) {
                    d.focus();
                    var f = document.selection.createRange();
                    if (f == null) {
                        return 0
                    }
                    var e = d.createTextRange(), g = e.duplicate();
                    e.moveToBookmark(f.getBookmark());
                    g.setEndPoint("EndToStart", e);
                    return g.text.length
                }
            }
            return 0
        }
    }(jQuery));

    $(function() {
       $("#anyNumber").numericInput({ allowFloat: true, allowNegative: true });
    });
</script>

2个解决方案:

使用表单验证器(例如jQuery验证插件)

在输入字段的onblur事件期间(即当用户离开字段时)执行检查,使用正则表达式:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>

请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。

使用这个DOM:

<input type = "text" onkeydown = "validate(event)"/>

还有这个脚本:

validate = function(evt)
{
    if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

...或者这个脚本,没有indexOf,使用两个for…

validate = function(evt)
{
    var CharValidate = new Array("08", "046", "039", "948", "235");
    var number_pressed = false;
    for (i = 0; i < 5; i++)
    {
        for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
        {
            if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
            {
                number_pressed = true;
            }
        }
    }
    if (number_pressed == false)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

我使用onkeydown属性而不是onkeypress,因为onkeydown属性是在onkeypress属性之前检查的。问题出在谷歌Chrome浏览器上。

与属性“onkeypress”,标签将不可控与“preventDefault”谷歌chrome,然而,与属性“onkeydown”,标签变成可控!

9 . TAB =>的ASCII码

第一个脚本的代码比第二个脚本少,但是ASCII字符数组必须包含所有的键。

第二个脚本比第一个脚本大得多,但是数组并不需要所有的键。数组每个位置的第一位数字是每个位置将被读取的次数。对于每一个读数,都将加1到下一个读数。例如: NCount = 0

48 + NCount = 48

NCount + +

48 + NCount = 49

NCount + +

...

48 + NCount = 57 在数字键只有10(0 - 9)的情况下,但如果它们是100万个,那么创建一个包含所有这些键的数组就没有意义了。

ASCII代码:

8 ==>(退格); 46 =>(删除); 37 =>(左箭头); 39 =>(右箭头); 48 - 57 =>(数字); 36 => (home); 35 => (end);