Borislav Hadzhiev
Fri Jan 28 2022·2 min read
Photo by Meiying Ng
Use the value
property to check if an input type="date" is empty, e.g.
if (!dateInput.value) {}
. The value
property stores the date formatted as
YYYY-MM-DD
or has an empty value if the user hasn't selected a date.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <label for="start">Input type Date:</label> <input type="date" id="date" name="trip-start" /> <button id="btn">Check</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { const dateInput = document.getElementById('date'); if (!dateInput.value) { console.log('Input type date is empty'); } else { console.log('Input type date is NOT empty'); console.log(dateInput.value); } });
We added a click
event listener to a btn
element, so a function is invoked
every time the button is clicked.
Inside of the function, we selected the
input
element with a type of date
.
The value
property in the input can be used to set or get the selected date.
This is why we used the
logical NOT (!)
operator to check if the value
property is falsy.
Here are some examples of using the logical NOT (!) operator.
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true
You can imagine that the logical NOT (!) operator first converts the value to a
boolean
and then flips the value.
true
, in all other cases it returns false
.Falsy values are: null
, undefined
, empty string, NaN
, 0
and false
.
If I open my browser and click on the button without selecting a date, I can see that the empty input string gets logged to the console.
If I now select a date in the input
element and click on the button again, I
get the message that the input
is NOT empty and the selected date, formatted
as YYYY-MM-DD
.
If you need to check if the input type="date" is NOT empty, you can remove the logical NOT (!) operator.
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { const dateInput = document.getElementById('date'); if (dateInput.value) { console.log('Input type date is NOT empty'); console.log(dateInput.value); } else { console.log('Input type date is empty'); } });
Now our if
statement checks if the date input
has a value.
If the input
stores a value, the value will be a string formatted as
YYYY-MM-DD
, which is truthy, so the if
statement will run.
Otherwise, if the input is empty, the else
block is ran.