【发布时间】: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