JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if an input type="date" is empty in JavaScript?

When a user selects a date on input type="date", then the value property of that input element will have a date as "YYYY-MM-DD". On the other hand, if a user does not select a date, then the value property is empty.

You can use this information to determine if the input type="date" is empty or not.

Here is the HTML code as an example.

index.html
<!DOCTYPE html>
<html>
<head>
  <title>Check input type="date" is empty</title>
</head>
<body>
  <input type="date" id="date-of-birth" name="date-of-birth" />
  <button id="btn">Submit</button>
  <script type="text/javascript" src="index.js"></script>
</body>
</html>

JavaScript code

index.js
let btn = document.getElementById("btn");

btn.addEventListener('click', (event)=>{
  let inputDate = document.getElementById('date-of-birth');
  if(!inputDate.value){
    console.log("Input type date is empty.");
  }else{
    console.log("Input type date is not empty.");
  }
});

Here, is the explanation of the code:

  • First of all, select input type="date" using document.getElementById().
  • After that, the value property is accessed, then the logical Not operator is used to check if input type="date" is empty.

Recommended Posts