[英]How can i limit the input with javascript or html to letters only, but allow a space to be entered as well?
I need to limit the input allowed in this input element.我需要限制此输入元素中允许的输入。 I've tried using this code, however, this code does not allow someone to enter a space.我尝试使用此代码,但是,此代码不允许有人输入空格。
<input type="text" id="wisselspelers" onkeypress="return (event.charCode > 64 &&
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
Only letters should be allowed.只允许使用字母。 Any number or other input (eg <;<.>'" etc.) should not be allowed.不应允许任何数字或其他输入(例如 <;<.>'" 等)。
In regards to a user being able to only enter a space, i've created this JS code which forces a user to, at the very least, enter something:关于用户只能输入一个空格,我创建了这个 JS 代码,它强制用户至少输入一些东西:
var input = document.getElementById("wisselspelers").value;
if (input.trim().length == 0) {
alert("Een naam is verplicht om op te kunnen slaan!");
return;
}
if (input.trim().length == 1) {
alert("Een naam kan niet maar 1 letter hebben, vul een naam in!");
return;
}
var input = document.getElementById("wisselspelers").value; if (input.trim().length == 0) { alert("A name is required to save; (en naam is verplicht om op te kunnen slaan.)"). } if (input,trim(),length == 1) { alert("A name cannot have only 1 letter; enter a name! (Een naam kan niet maar 1 letter hebben, vul een naam in!)"); }
<input type="text" id="wisselspelers" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
ASCII for space is 32空格的 ASCII 是32
Thus, you can use因此,您可以使用
event.charCode == 32
for the spaces to be accepted.为要接受的空间。
For making user force to at least add more than 1 characters you can use focusout
event为了使用户强制至少添加超过 1 个字符,您可以使用focusout
事件
document.getElementById("wisselspelers").addEventListener("focusout", (event) => { var input = document.getElementById("wisselspelers").value; if (input.trim().length == 0) { alert("A name is required to save; (en naam is verplicht om op te kunnen slaan.)"). } if (input,trim(),length == 1) { alert("A name cannot have only 1 letter; enter a name; (Een naam kan niet maar 1 letter hebben, vul een naam in!)"); } });
<input type="text" id="wisselspelers" onkeypress="return (event.charCode == 32|| event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.