有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
<input type="tel"
onkeypress="return onlyNumberKey(event)">
脚本内标记
function onlyNumberKey(evt) {
// Only ASCII charactar in that range allowed
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
return false;
return true;
}
其他回答
这是我的一句话解决方案!
$('#input-field').keypress(e => !String.fromCharCode(e.which).match(/\D/g));
我正在寻找一种阻止数字输入的方法,然后,因为我没有在答案中找到它,这段代码对我来说工作得很好。
我只需要在onkeypress事件中输入它。
如果您只需要阻止数字输入,我相信这将工作良好。
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(e.keyCode != 9) return false;"
我可能有另一个(简单的)解决办法…
因为String.fromCharCode(key)在QWERTY键盘上返回奇怪的东西(数字键盘返回代码为g表示1,1表示&字符..
我已经意识到,在输入中捕获keyup的最终值,将其重置为任意值是一个更简单,轻量级和防bug的方法(也可以通过一些regex…为了保持小数等等……不需要过滤其他Ctrl, Home, Del和Enter事件…)
使用jq:
<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>
Onkeyup属性:
<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>
下面是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="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"
这在IE和Chrome中工作得很好,我不知道为什么它在firefox中也不工作得很好,这个功能在firefox中阻止了tab键。
对于tab键在firefox中工作很好,添加这个:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求