有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
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不会在任何浏览器中运行。
其他回答
下面是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">
正则表达式和匹配函数可以很好地处理这种情况。例如,我使用下面的代码来验证图上作为坐标的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();
}
}
你可以附加到key down事件,然后根据你需要过滤键,例如:
<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);" type="text">
实际的JavaScript处理程序是:
function validateNUM(e,field)
{
var key = getKeyEvent(e)
if (specialKey(key)) return true;
if ((key >= 48 && key <= 57) || (key == 46)){
if (key != 46)
return true;
else{
if (field.value.search(/\./) == -1 && field.value.length > 0)
return true;
else
return false;
}
}
function getKeyEvent(e){
var keynum
var keychar
var numcheck
if(window.event) // IE
keynum = e.keyCode
else if(e.which) // Netscape/Firefox/Opera
keynum = e.which
return keynum;
}
你也可以比较输入值(默认情况下被视为字符串)和它本身被强制为数字,比如:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
然而,你需要绑定到事件,如keyup等。
这里是一个非常简短的解决方案,不使用已弃用的keyCode或,不阻塞任何非输入键,并使用纯javascript。(在Chromium 70.0.3533, Firefox 62.0和Edge 42.17134.1.0中测试)
HTML:
<input type="text" onkeypress="validate(event)">
JS:
function validate(ev) {
if (!ev) {
ev = window.event;
}
if (!ev.ctrlKey && ev.key.length === 1 && (isNaN(+ev.key) || ev.key === " ")) {
return ev.preventDefault();
}
}