Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an HTML input element is empty or has no value entered by user

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 } 

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.

like image 424
zik Avatar asked Jan 10 '12 12:01

zik


People also ask

How do you know if a input is empty react?

To check if an input is empty in React:Call the trim() method on the field's value. Access the length property on the value. If the field's value has a length of 0 , then it is empty, otherwise it isn't.

How do you validate a text field in HTML?

To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.


2 Answers

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.

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!"); } 
like image 92
Jonas Høgh Avatar answered Sep 27 '22 18:09

Jonas Høgh


getElementById will return false if the element was not found in the DOM.

var el = document.getElementById("customx"); if (el !== null && el.value === "") {   //The element was found and the value is empty. } 
like image 31
Dreendle Avatar answered Sep 27 '22 18:09

Dreendle