检查HTML输入元素是否为空或用户未输入任何值
与>这里的问题.我可以检查DOM中的元素是否具有值?我正在尝试将其放入'if'语句中,不确定我的方法是否正确.去吧:
Related to this question 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:
if (document.getElementById('customx')){
//do something
}
或者应该是
if (document.getElementById('customx') == ""){
//do something
}
按值表示, customx
是一个文本输入框.如何检查此字段是否未输入文本.
By value I mean, customx
is a text input box. How can I check if this field has no text entered.
getElementById
方法返回一个Element对象,您可以使用该对象与该元素进行交互.如果找不到该元素,则返回 null
.对于输入元素,对象的 value
属性在value属性中包含字符串.
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.
通过使用&&
运算符短路以及在布尔上下文中将 null
和空字符串都视为"falsey"这一事实,我们可以将对元素是否存在以及是否存在值数据的检查组合如下:
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:
var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
alert("My input has a value!");
}