[英]Using Javascript to limit my html input to only text and alerting the user otherwise?
So basically I have created input fields in HTML for a persons first and last names. 因此,基本上我已经在HTML中为人员的姓氏和名字创建了输入字段。 I want this field to limit their inputs to only text and give them an alert otherwise using vanilla JS please. 我希望此字段将他们的输入限制为仅文本,并给他们警报,否则请使用香草JS。
Here is the HTML code: 这是HTML代码:
<div>
First Name:<br> <input id="name" type="text" placeholder="Type Here" pattern="[A-Za-z]"><br>
Last Name:<br> <input id="name" type="text" placeholder="Type Here" pattern="[A-Za-z]">
</div>
As you can see I previously tried to limit the input by using the pattern="" method I saw in another post but couldn't get it to work. 如您所见,我以前曾尝试使用在另一篇文章中看到的pattern =“”方法来限制输入,但无法使其正常工作。 Advice on that would be much appreciated as well. 对此的建议也将不胜感激。
And here is my JS function as it stands now: 这是我现在的JS函数:
var nameinput=document.getElementById('name').value;
var input=function(field){
if(isNaN(field)===false || field===""){
alert('Please Enter Your Name');
return false;
}
}
input(nameinput)
It's probably something obvious. 这可能很明显。 I'm pretty new to JS but any help would be greatly appreciated! 我对JS很陌生,但是任何帮助将不胜感激!
If you want it to check all the time, try to implement a custom onChange
callback ie <input type="text" name="firstName" onChange="verif()">
, or, if you want it to verify only at submit time, add onSubmit="verif()"
to your form. 如果您希望它一直进行检查,请尝试实现自定义onChange
回调,即<input type="text" name="firstName" onChange="verif()">
,或者,如果您仅希望在提交时进行验证时间,将onSubmit="verif()"
到您的表单中。 For both case the verif() function looks like 对于这两种情况, verif()函数看起来像
function verif(){
var firstName = document.getElementByName("firstName")[0].value;
if(!firstName.match(/[\A-Za-z]+/i)) {
alert("You can only enter characters");// Or whatever message
document.getElementByName("firstName")[0].focus();
}
var lastName = document.getElementByName("lastName")[0].value;
if(!lastName.match(/[\A-Za-z]+/i)) {
alert("You can only enter characters");// Or whatever message
document.getElementByName("lastName")[0].focus();
}
}
By the way, this code assume that you use the name property with your inputs, which you should alway use with inputs. 顺便说一句,此代码假定您在输入中使用了name属性,应该始终将其与输入一起使用。 You also shouldn't use two time the same id. 您也不应使用两次相同的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.