有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
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:)
其他回答
这可以立即删除任何坏字符,只允许一个点,是短的,并允许退格等:
$('.numberInput').keyup(function () {
s=$(this).val();
if (!/^\d*\.?\d*$/.test(s)) $(this).val(s.substr(0,s.length-1));
});
ReactJS:
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
还有一个例子,对我来说很有用:
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的例子
下面是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">
HTML5支持正则表达式,所以你可以使用这个:
<input id="numbersOnly" pattern="[0-9.]+" type="text">
警告:某些浏览器还不支持此功能。
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 向HTML表中添加水平滚动条
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- 在notepad++中格式化代码
- 表单中包含表单,可以吗?
- 如何创建表只使用<div>标签和Css
- html5 - canvas元素-多层
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?