【问题标题】:How to block user type some characters to input?如何阻止用户输入一些字符来输入?
【发布时间】:2019-09-19 20:01:09
【问题描述】:

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

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

【问题讨论】:

标签: javascript html web


【解决方案1】:

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

document.querySelector('[name=txtName]').addEventListener('input',function(){
    this.value = this.value.replace("'", '');
});
<div class="col-md-4">
  <input name="txtName" type="text"  class="form-control" placeholder="Name">
</div>

【讨论】:

    【解决方案2】:

    试试这个:

    document.getElementById("input").onkeypress = function(e) {
        /^[a-zA-Z0-9]+$/.test(this.value)
    };
    &lt;input type="text" id="input"&gt;

    更改正则表达式以匹配您想要的字符,目前只有字母(小写和大写)和数字。

    来自How to block special characters in HTML input field?的代码

    【讨论】:

      【解决方案3】:
      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;
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多