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


当前回答

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);"/>

其他回答

下面是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">

对于喜欢说俏皮话的人。

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";

:)

这是我的一句话解决方案!

$('#input-field').keypress(e => !String.fromCharCode(e.which).match(/\D/g));

以下是我仅针对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, ""));
}

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

允许的字符

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">

如果不行就告诉我。