检查 Javascript 中的文本框是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14659098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a textbox is empty in Javascript
提问by Vishal Suthar
This is my code which was supposed to raise an alertmessage if the textbox is left empty:
这是我的代码,alert如果文本框留空,它应该会引发一条消息:
function a(id)
{
var n=document.getElementById(id).value;
if (n.length < 1)
{
window.alert("Field is blank");
return false;
}
}
The bug I'm getting is that the field is not getting verified onChangethe first time. But when the text box is filled with some data and erased, now the OnChangefires, and the alertmessage is displayed. How can I fix this bug?
我得到的错误是该领域没有onChange第一次得到验证。但是当文本框填充一些数据并被擦除时,现在会OnChange触发,并alert显示消息。我该如何修复这个错误?
回答by Vishal Suthar
onchangewill work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.
onchange只有当文本框的值与之前的值相比发生变化时才会起作用,所以第一次它不起作用,因为状态没有改变。
So it is better to use onblurevent or on submitting the form.
所以最好使用onblur事件或提交表单。
function checkTextField(field) {
document.getElementById("error").innerText =
(field.value === "") ? "Field is empty." : "Field is filled.";
}
<input type="text" onblur="checkTextField(this);" />
<p id="error"></p>
回答by arvin_codeHunk
your validation should be occur before your event suppose you are going to submit your form.
假设您要提交表单,您的验证应该在您的活动之前进行。
anyway if you want this on onchange, so here is code.
无论如何,如果您希望在onchange 上进行此操作,那么这里是代码。
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}

