Verify that the HTML input element is empty or does not have a value entered by the user.

In connection with this issue. Can I check if an element in the DOM has a value or not? I am trying to include it in the expression "if" and am not sure if my approach is correct. Here:

if (document.getElementById('customx')){ //do something } 

Or it should be:

 if (document.getElementById('customx') == ""){ //do something } 

EDIT: By value, I mean customx is an input text box. How to check if this field is entered?

+6
source share
5 answers

The getElementById method returns an Element that can be used to interact with an element. If the item is not found, null returned. In the case of an input element, the value property of the object contains a string in the value attribute.

Using the fact that the short circuits of the && operator and that both null and the empty string are considered β€œfalse” in a Boolean context, we can combine checks for the existence of an element and the presence of value data as follows:

 var myInput = document.getElementById("customx"); if (myInput && myInput.value) { alert("My input has a value!"); } 
+14
source

getElementById will return false if the item is not found in the DOM.

 var el = document.getElementById("customx"); if (el !== null && el.value === "") { //The element was found and the value is empty. } 
+2
source
 var input = document.getElementById("customx"); if (input && input.value) { alert(1); } else { alert (0); } 
+2
source

Your first was basically right. This, FYI, is bad. It performs an equality check between the DOM node and the string:

 if (document.getElementById('customx') == ""){ 

DOM nodes are actually their own JavaScript object. Thus, this comparison will never work at all, since it compares the equality of two different data types.

0
source

Do you want to:

 if (document.getElementById('customx').value === ""){ //do something } 

The value property will give you a string value, and you need to compare it with an empty string.

0
source

Source: https://habr.com/ru/post/905613/


All Articles