Last updated: Mar 6, 2024
Reading timeยท3 min
Use the value
property to check if an input type="date" is empty.
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.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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 button element, so a function is invoked
every time the button is clicked.
Inside 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.
If the user hasn't selected a date, the value will be empty.
Most commonly an empty value is represented by an empty string, but how different browsers implement this may vary.
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 it.
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 runs.
You can learn more about the related topics by checking out the following tutorials: