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


当前回答

解决这个问题的一个简单方法是实现一个jQuery函数来验证文本框中输入的字符,例如:

你的html代码:

<input class="integerInput" type="text">

和使用jQuery的js函数

$(function() {
    $('.integerInput').on('input', function() {
      this.value = this.value
        .replace(/[^\d]/g, '');// numbers and decimals only

    });
});

$(函数(){ $('.integerInput').on('input', function() { 这一点。Value = this.value .replace(/[^\d]/g, ");//只能输入数字和小数 }); }); <脚本 src = " https://code.jquery.com/jquery-2.2.4.min.js " 诚信= " sha256-BbhdlvQf / xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44 = " crossorigin =“匿名”> > < /脚本 <input type="text" class="integerInput"/>

其他回答

这里有一个简单的例子,它只允许有一个小数,不能再多了。输入事件使用regex替换基于以下两种模式的文本:

删除任何不是数字或点的东西 删除点的任何第二个实例

<input type="text" oninput="this. "Value = this.value.replace(/[^0-9。.replace) / g,”) (/(\..*?)\..* / g, 1美元);”/>

正如下面有人评论的那样,上面的解决方案不处理前导零。如果你的特定用例要求这些是不允许的,你可以像这样添加到上面的模式:

<input type="text" oninput="this. "Value = this.value.replace(/[^0-9。.replace) / g,”) (/(\..*?)\..* / g, 1美元).replace(/ ^ 0 ^。] /, ' 0 ');“/>

这将允许0.123或。123,但不允许0123或00.123。

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

你可以用以下方法替换Shurok函数:

$(".numeric").keypress(function() {
    return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});
<input name="amount" type="text" value="Only number in here"/> 

<script>
    $('input[name=amount]').keyup(function(){
        $(this).val($(this).val().replace(/[^\d]/,''));
    });
</script>

Use:

<script>
    function onlyNumber(id){ 
        var DataVal = document.getElementById(id).value;
        document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
    }
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">

如果你想在按下键后更新一个值,你可以改变onChange为onKeypress, onKeyDown或onKeyup。但是事件onKeypress不会在任何浏览器中运行。