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


当前回答

还有一个例子,对我来说很有用:

function validateNumber(event) {
    var key = window.event ? event.keyCode : event.which;
    if (event.keyCode === 8 || event.keyCode === 46) {
        return true;
    } else if ( key < 48 || key > 57 ) {
        return false;
    } else {
        return true;
    }
};

也附加到按键事件

$(document).ready(function(){
    $('[id^=edit]').keypress(validateNumber);
});

和HTML:

<input type="input" id="edit1" value="0" size="5" maxlength="5" />

下面是一个jsFiddle的例子

其他回答

请找到下面提到的解决方案。在此用户只能输入数值,同时用户不能在输入中复制、粘贴、拖放。

允许的字符

0,1,2,3,4,5,6,7,8,9

不允许字符和字符通过事件

字母的值 特殊字符 复制 粘贴 拖 下降

$(document).ready(function() { $('#number').bind("cut copy paste drag drop", function(e) { e.preventDefault(); }); }); function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="form-control" name="number" id="number" onkeypress="return isNumberKey(event)" placeholder="Enter Numeric value only">

如果不行就告诉我。

对于喜欢说俏皮话的人。

string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

我在输入type="text"上使用这段代码,并使用AngularJS在按键时激活,但如果喜欢,可以使用jQuery。只需将此代码放入一个函数中,该函数以某种方式通过按键激活。

它只允许数字,数字+十进制,数字+十进制+数字。

CODE

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";

testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";

testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";

testFour = "622632463.23464236326324363"
=> "622632463.23";

这是为美国货币构建的,但它可以更改为允许超过两个小数点后的第一个小数,如下所示…

改变了代码

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');

testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";

:)

下面是emkey08的JavaScript Wiki答案的一个面向对象的重新实现,它使用了一个EventListener对象实现。(参见:MDN web docs EventListener)

在某种程度上,它可以防止为每个过滤后的输入元素重复匿名事件处理程序函数声明,同时仍然允许它通过可选的回调。

/** * Base input {@see Element} {@see EventListener} filter abstract class * * @implements EventListener */ class AbstractInputFilter { /** * Attach the input filter to the input {@see Element} * * @param inputElement The input {@see Element} to filter * @param isValid - The callback that determines if the input is valid. * @throws Error */ constructor(inputElement, isValid = null) { // Abstract class if (this.constructor === AbstractInputFilter) { throw new Error("Object of Abstract Class cannot be created"); } if (typeof isValid === "function") { this.isValid = isValid; } for (const event of ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"]) { inputElement.addEventListener(event, this); } } /** * Checks the value is valid * * @callback isValid default call-back that will throw * an {Error} if not implemented by extending this * {AbstractInputFilter} class. * * @param value The value to check * @returns {boolean} * @throws Error */ isValid(value) { throw new Error('must be implemented by callback!'); } /** * Handles the {@see event} dispatched by * the {@see EventTarget} object from the input {@see Element} * to filter its contant while it is being filled. * * @param event the {@see event} dispatched by * the {@see EventTarget} input {@see Element} * @override */ handleEvent(event) { const inputElement = event.currentTarget; if (this.isValid(inputElement.value)) { inputElement.oldValue = inputElement.value; inputElement.oldSelectionStart = inputElement.selectionStart; inputElement.oldSelectionEnd = inputElement.selectionEnd; } else if (inputElement.hasOwnProperty("oldValue")) { inputElement.value = inputElement.oldValue; inputElement.setSelectionRange( inputElement.oldSelectionStart, inputElement.oldSelectionEnd); } else { this.value = ""; } } } /** * Generic Input element {@see EventListener} filter * * @extends AbstractInputFilter * It needs the {@see AbstractInputFilter~isValid} callback * to determine if the input is valid. */ class InputFilter extends AbstractInputFilter {} /** * Unsigned Integer Input element {@see EventListener} filter * @extends AbstractInputFilter */ class UIntInputFilter extends AbstractInputFilter { isValid(value) { return /^\d*$/.test(value); } } /** * Unsigned Float Input element {@see EventListener} filter * @extends AbstractInputFilter */ class UFloatInputFilter extends AbstractInputFilter { isValid(value) { return /^\d*\.?\d*$/.test(value); } } // Filter with pre-made InputFilters (re-use the filter) new UIntInputFilter(document.getElementById("UInt")); new UFloatInputFilter(document.getElementById("UFloat")); // Filter with custom callback filter anonymous function new InputFilter(document.getElementById("AlNum"), function(value) { return /^\w*$/.test(value); }); <label>Unsigned integer: </label><input id="UInt"><br/> <label>Unsigned float: </label><input id="UFloat"><br/> <label>AlphaNumeric (no special characters): </label><input id="AlNum">

我正在寻找一种阻止数字输入的方法,然后,因为我没有在答案中找到它,这段代码对我来说工作得很好。

我只需要在onkeypress事件中输入它。

如果您只需要阻止数字输入,我相信这将工作良好。

onkeypress="if(event.which &lt; 48 || event.which &gt; 57 ) if(event.which != 8) if(e.keyCode != 9) return false;"

下面的代码还将检查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">