0

I want to show current date on input field date.My code is down below

HTML:

<div class=\"col-lg-4\">
    <label>Date</label>
     <input type=\"date\"  name=\"dateto1\" id=\"dateto1\" class=\"form-control\">
    </div>

JAVASCRIPT:

<script type="text/javascript">

 var today = new Date();

      var dd = today.getDate();
      var mm = today.getMonth()+1; //January is 0!
      var yyyy = today.getFullYear();

      if(dd<10) {
          dd = '0'+dd
      } 

      if(mm<10) {
          mm = '0'+mm
      } 

      // today = yyyy + '/' + mm + '/' + dd;
       today = mm + '/' + dd + '/' + yyyy;

      console.log(today);
      document.getElementById('dateto1').value = today;

    }


    window.onload = function() {

      getDates();
    };
</script>

this code is working fine if i use input type "text" but for type date its not working.Please guide me to solve this issue.

Thanks

2 Answers2

1

You should use the yyyy-MM-dd format:

var today = new Date();

      var dd = today.getDate();
      var mm = today.getMonth()+1; //January is 0!
      var yyyy = today.getFullYear();

      if(dd<10) {
          dd = '0'+dd
      } 

      if(mm<10) {
          mm = '0'+mm
      } 

      // today = yyyy + '/' + mm + '/' + dd;
       today = yyyy + '-' + mm + '-' + dd;

      console.log(today);
      document.getElementById('dateto1').value = today;
<div class="col-lg-4">
<label>Date</label>
<input type="date"  name="dateto1" id="dateto1" class="form-control"></div>
Silvio Biasiol
  • 856
  • 8
  • 14
0

The problem may be with the date format Use yyyy-mm-dd format.

Also there is no getDates function in the code

var today = new Date();

var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();

if (dd < 10) {
  dd = '0' + dd
}

if (mm < 10) {
  mm = '0' + mm
}

// today = yyyy + '/' + mm + '/' + dd;
today = `${yyyy}-${mm}-${dd}`;
document.getElementById('dateto1').value = today;
<div class="col-lg-4">
  <label>Date</label>
  <input type="date" name="dateto1" id="dateto1" class="form-control">
</div>
brk
  • 48,835
  • 10
  • 56
  • 78