Javascript 如何阻止用户输入一些字符?

Javascript 如何阻止用户输入一些字符?,javascript,html,web,Javascript,Html,Web,我有一个web应用程序,有一个输入用户可以在其中添加一些名称,但我不希望用户输入撇号“符号。当用户按下“符号”时,html不必插入字符。我是html新手,还有js代码文件 <div class="col-md-4"> <input name="name" type="text" class="form-control" placeholder="Name"> </div> 试试这个: document.getElementById(“输入”).

我有一个web应用程序,有一个输入用户可以在其中添加一些名称,但我不希望用户输入撇号
符号。当用户按下“符号”时,html不必插入字符。我是html新手,还有js代码文件

<div class="col-md-4">
    <input name="name" type="text"  class="form-control" placeholder="Name">
</div>

试试这个:

document.getElementById(“输入”).onkeypress=函数(e){
/^[a-zA-Z0-9]+$/.测试(该值)
};

您可以将值中的字符替换为空字符。我还建议您为控件使用其他名称,因为名称是JavaScript中的关键字:

document.querySelector('[name=txtName]')。addEventListener('input',function(){
this.value=this.value.replace(“,”);
});

var digitsOnly = /[1234567890]/g;
var floatOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;

function restrictCharacters(myfield, e, restrictionType) {
    if (!e) var e = window.event
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    // if they pressed esc... remove focus from field...
    if (code==27) { this.blur(); return false; }
    // ignore if they are press other keys
    // strange because code: 39 is the down key AND ' key...
    // and DEL also equals .
    if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
        if (character.match(restrictionType)) {
            return true;
        } else {
            return false;
        }
    }
}