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


当前回答

当涉及到万无一失的用户体验时,人们应该总是尝试保持一个“用户智力”的参考点。

While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.

同样,对于表单,验证和错误消息显示几乎是必需的。所以,这些条款可能已经存在了。算法如下:

On losing-focus or form-submission, do following. 1.1. Read content from the input and apply parseFloat to result 1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584". 1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2. 1.4. Else, do nothing.

该方法还为您提供了额外的优势,可以根据最小值、最大值、小数点等执行验证。只需要对步骤1.2之后的结果执行这些操作。

缺点:

输入将允许用户输入任何值,直到焦点丢失或表单提交为止。但如果填写说明足够清楚,90%的情况下可能不会出现这种情况。 如果步骤1.3用于显示警告,则可能会被用户忽略,并可能导致无意的输入提交。抛出错误或正确显示警告可以解决这个问题。 速度。这可能比regex方法慢几微秒。

优点: 假设用户有基本的阅读和理解知识,

高度可定制的选项。 工作跨浏览器和独立于语言。 利用表单中已有的功能来显示错误和警告。

其他回答

HTML5支持正则表达式,所以你可以使用这个:

<input id="numbersOnly" pattern="[0-9.]+" type="text">

警告:某些浏览器还不支持此功能。

给输入字段一个类(<input class="digit"…>)和使用jquery如下所示。

jQuery(document).ready(function () {
            jQuery('input.digit').live('input keyup',function(e){ jQuery(this).val(jQuery(this).val().replace( /[^\d]/g ,'')); });
});

上面的代码还可以禁用Ctrl+V笔画和右键单击笔画中的特殊字符。

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

$(".numeric").keypress(function() {
    return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});

JavaScript代码:

function validate(evt)
{
    if(evt.keyCode!=8)
    {
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
        var regex = /[0-9]|\./;
        if (!regex.test(key))
        {
            theEvent.returnValue = false;

            if (theEvent.preventDefault)
                theEvent.preventDefault();
            }
        }
    }

HTML代码:

<input type='text' name='price' value='0' onkeypress='validate(event)'/>

工作完美,因为退格键码是8,正则表达式不让它,所以这是一个简单的方法来绕过bug:)

下面的代码还将检查PASTE事件。 取消“ruleSetArr_4”的注释,并在“ruleSetArr”中添加(concate)以允许浮点数。 简单的复制/粘贴功能。用参数中的input元素调用它。 例如:inputIntTypeOnly($('输入[name = " inputName "] '))

function inputIntTypeOnly(elm){ elm.on("keydown",function(event){ var e = event || window.event, key = e.keyCode || e.which, ruleSetArr_1 = [8,9,46], // backspace,tab,delete ruleSetArr_2 = [48,49,50,51,52,53,54,55,56,57], // top keyboard num keys ruleSetArr_3 = [96,97,98,99,100,101,102,103,104,105], // side keyboard num keys ruleSetArr_4 = [17,67,86], // Ctrl & V //ruleSetArr_5 = [110,189,190], add this to ruleSetArr to allow float values ruleSetArr = ruleSetArr_1.concat(ruleSetArr_2,ruleSetArr_3,ruleSetArr_4); // merge arrays of keys if(ruleSetArr.indexOf() !== "undefined"){ // check if browser supports indexOf() : IE8 and earlier var retRes = ruleSetArr.indexOf(key); } else { var retRes = $.inArray(key,ruleSetArr); }; if(retRes == -1){ // if returned key not found in array, return false return false; } else if(key == 67 || key == 86){ // account for paste events event.stopPropagation(); }; }).on('paste',function(event){ var $thisObj = $(this), origVal = $thisObj.val(), // orig value newVal = event.originalEvent.clipboardData.getData('Text'); // paste clipboard value if(newVal.replace(/\D+/g, '') == ""){ // if paste value is not a number, insert orig value and ret false $thisObj.val(origVal); return false; } else { $thisObj.val(newVal.replace(/\D+/g, '')); return false; }; }); }; var inptElm = $('input[name="inputName"]'); inputIntTypeOnly(inptElm); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" name="inputName" value="1">