input type="date" set a default value to date today

Viewed 11145

How can I set an input type="date" value set to default value equals date today?

this is my HTML code, what's the best way to do it?

<div class="form-group col-6">
    <label for="inputEmail4">Start date</label>
        <input type="date" value="fsd" id="startdateId" class="form-control" required>
 </div>

2 Answers

try it

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;

document.getElementById("startdateId").value = today;
<div class="form-group col-6">
  <label for="inputEmail4">Start date</label>
  <input type="date" value="fsd" id="startdateId" class="form-control" required>
</div>

Like any HTML input field, the browser will leave it empty unless a default value is specified with the value attribute.

Unfortunately, HTML5 doesn't provide a way of specifying 'today' in the value attribute. You need Javascript to do so.

document.getElementById('startdateId').value = new Date().toISOString().slice(0, 10);
<div class="form-group col-6">
  <label for="inputEmail4">Start date</label>
     <input type="date" value="fsd" id="startdateId" class="form-control" required>
</div>

Related