【问题标题】:HTML Input field: remove spaces with jQuery 3.2.1HTML 输入字段:使用 jQuery 3.2.1 删除空格
【发布时间】:2018-01-18 20:57:44
【问题描述】:

我正在编写一个 HTML / PHP 表单来注册用户。

通过以下代码,我到达了它,输入字段中不会出现空格。

<!DOCTYPE html>
<html>
<head>
<script>
    function stripspaces(input)
    {
        input.value = input.value.replace(/\s/gi,"");
        return true;
    }
</script>
</head>
<body>
    Enter your username: <input onkeydown="javascript:stripspaces(this)" name="field_with_no_spaces" type="text" />
</body>
</html>

但我读到 (Disable spaces in Input, AND allow back arrow?) 有一个更好的方法来做到这一点。我试过了:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $("input#UserName").on({
            keydown: function(e) {
                if (e.which === 32)
                    return false;
            },
            change: function() {
                this.value = this.value.replace(/\s/g, "");
            }
        });
    </script>
</head>
<body>
    Enter your username: <input id="UserName" name="UserName" type="text" />
</body>
</html>

但它不起作用,有人可以帮助我吗?是不是因为我的jQuery版本?

谢谢,

【问题讨论】:

  • 你仍然应该使用 php 进行验证,因为任何 JS 都可以轻松绕过 ;)

标签: javascript jquery html


【解决方案1】:

您需要在创建 DOM 元素之后添加您的 js 代码(因此就在您的示例中的结束 body 标记之前),或者使用“$function”声明。否则,当评估 $("input#UserName") 时,还没有创建输入,因此不会附加处理程序

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
    $("input#UserName").on({
        keydown: function(e) {
            if (e.which === 32)
                return false;
        },
        change: function() {
            this.value = this.value.replace(/\s/g, "");
        }
    });
    })
</script>
</head>
<body>
Enter your username: <input id="UserName" name="UserName" type="text" />
</body>
</html>

【讨论】:

  • 感谢您的回答。现在它起作用了:)。我欠你一杯咖啡。
【解决方案2】:

您忘记将代码包装在 .ready() 回调中,请参阅 sn-p。

当前你的代码执行时,DOM还没有加载到内存中解析,所以JavaScript代码调用了还不存在的元素,因此无法添加事件监听器。

<input onkeydown="javascript:stripspaces(this)" name="field_with_no_spaces" type="text" id="" />

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("input#UserName").on({
        keydown: function(e) {
          if (e.which === 32)
            return false;
        },
        change: function() {
          this.value = this.value.replace(/\s/g, "");
        }
      });
    });
  </script>
</head>
<body>
  Enter your username: <input id="UserName" name="UserName" type="text" />
</body>
</html>

【讨论】:

    【解决方案3】:

    onkeypress='return event.charCode != 32'

    这将阻止输入space,并且不依赖于 JQuery。

    但是你还是应该用 php 来验证,因为任何 JS 都可以很容易地被绕过 ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多