检查HTML输入元素是否为空或用户未输入任何值 [英] Check if an HTML input element is empty or has no value entered by user

查看:68
本文介绍了检查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!");
}

这篇关于检查HTML输入元素是否为空或用户未输入任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆