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.
This question is related to
javascript
html
dom
var input = document.getElementById("customx");
if (input && input.value) {
alert(1);
}
else {
alert (0);
}
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.
}
You want:
if (document.getElementById('customx').value === ""){
//do something
}
The value
property will give you a string value and you need to compare that against an empty string.
Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:
if (document.getElementById('customx') == ""){
DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.
Source: Stackoverflow.com