简体   繁体   English

跨浏览器代码以使用Javascript限制用户输入

[英]Cross browser code to restrict user input using Javascript

I found this code through Stack Overflow to restrict users from putting numbers in a textbox, however it only works in Chrome and IE. 我通过Stack Overflow找到了这段代码,以限制用户在文本框中输入数字,但是它仅在Chrome和IE中有效。 Anyone know of any cross browser code to do this? 有人知道任何跨浏览器代码可以做到这一点吗? Note: we've already added the global attribute and it didn't work at all, this was the only one that fully worked in Chrome and IE. 注意:我们已经添加了global属性,它根本不起作用,这是唯一在Chrome和IE中完全起作用的属性。

<input type="text" onkeyup="this.value = this.value.replace(/[^a-z]/, '')" />

You want to catch onkeydown that is when the character gets inserted, not on onkeyup . 您想捕获插入字符时的onkeydown ,而不是onkeyup You should also instead of removing the number, just prevent it from getting inserted with event.preventDefault() 您还应该删除数字,而不是删除它,而只是用event.preventDefault()插入它。

 <p> <input type="text" onkeydown="event.key.match(/\\d/) && event.preventDefault()" /> </p> 

One thing I would recommend is removing the code from the html and putting it in a function so it is reusable like this: 我建议的一件事是从html中删除代码,并将其放入函数中,以便可重复使用,如下所示:

 // Wait till the dom is loaded document.addEventListener('DOMContentLoaded', function(e) { // Add the event to each input that has `data-type="number"` document.querySelectorAll('[data-type=number]').forEach(function(input) { // Add the event to the input input.addEventListener('keydown', number) }) }) function number(event) { event.key.match(/\\d/) && event.preventDefault() } 
 <p> <input type="text" data-type="number" /> </p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM