Javascript 检查 HTML 输入元素是否为空或没有用户输入的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8803412/
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
Check if an HTML input element is empty or has no value entered by user
提问by zik
Related to thisquestion here. Can I check if an element in the DOM has a value or not? I'm trying to put it into an 'if' statement and not sure if my approach is correct. Here goes:
与此问题相关的here。我可以检查 DOM 中的元素是否有值吗?我正在尝试将其放入“if”语句中,但不确定我的方法是否正确。开始:
if (document.getElementById('customx')){
//do something
}
Or should it be:
或者应该是:
if (document.getElementById('customx') == ""){
//do something
}
EDIT: By value I mean, customx
is a text input box. How can I check if this field has no text entered.
编辑:我的意思是,值customx
是一个文本输入框。如何检查此字段是否未输入文本。
回答by Jonas H?gh
The getElementById
method returns an Element object that you can use to interact with the element. If the element is not found, null
is returned. In case of an input element, the value
property of the object contains the string in the value attribute.
该getElementById
方法返回一个 Element 对象,您可以使用该对象与元素进行交互。如果未找到该元素,null
则返回。对于 input 元素,value
对象的属性包含 value 属性中的字符串。
By using the fact that the &&
operator short circuits, and that both null
and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:
通过使用&&
运算符短路的事实,并且null
在布尔上下文中两者和空字符串都被认为是“假的”,我们可以将元素存在和值数据存在的检查组合起来,如下所示:
var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
alert("My input has a value!");
}
回答by Dreendle
getElementById will return false if the element was not found in the DOM.
如果在 DOM 中找不到该元素,则 getElementById 将返回 false。
var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
//The element was found and the value is empty.
}
回答by MarShalL89PL
var input = document.getElementById("customx");
if (input && input.value) {
alert(1);
}
else {
alert (0);
}
回答by Quentin
You want:
你要:
if (document.getElementById('customx').value === ""){
//do something
}
The value
property will give you a string value and you need to compare that against an empty string.
该value
属性将为您提供一个字符串值,您需要将其与空字符串进行比较。
回答by Mike Thomsen
Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:
你的第一个基本上是对的。仅供参考,这很糟糕。它在 DOM 节点和字符串之间进行相等性检查:
if (document.getElementById('customx') == ""){
DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.
DOM 节点实际上是它们自己的 JavaScript 对象类型。因此,这种比较根本不会起作用,因为它对两种截然不同的数据类型进行相等比较。