且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查HTML输入元素是否为空或用户未输入任何值

更新时间:2023-01-11 14:00:53

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!");
}