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.
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.
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.
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!"); }
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. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With