2

var today = new Date();
var dd = today.getDate();
var mm=today.getMonth();
mm++;
var yyyy =today.getFullYear();
// alert(mm);
var datee=yyyy+'-'+mm+'-'+dd;
$('#form_date').val(datee);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='date' id='form_date'>

i just need to auto select the current date in input type date i get the year,month and date from get function but when i am trying to put them in value it's not working

vivek modi
  • 487
  • 1
  • 5
  • 19
  • Possible duplicate of [set date in input type date](https://stackoverflow.com/questions/12346381/set-date-in-input-type-date)(See also: https://stackoverflow.com/questions/563406/add-days-to-javascript-date) – Tibrogargan Apr 23 '19 at 05:09
  • No they are giving the hole date with time i need just time to set in input type date – vivek modi Apr 23 '19 at 05:11
  • That's not what your question asks. Perhaps you want to re-word it. – Tibrogargan Apr 23 '19 at 05:12
  • no my question is clearly saying that i want to select current date for input type date through javascript – vivek modi Apr 23 '19 at 05:14

2 Answers2

2

This code is not working because it doesn't find the correct dom element when it run. So wrap your code inside $(document).ready(function(){}) function.

Veeramani
  • 92
  • 10
2

Single digit months and days should start with a zero:

//<![CDATA[
/* external.js */
function makeFormDate(dateInstance){
  var dt = dateInstance instanceof Date ? dateInstance : new Date;
  return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
}
$(function(){
  $('#form_date').val(makeFormDate());
});
//]]>
<script src=''></script>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <input id='form_date' type='date' value='' />
</body>
</html>
StackSlave
  • 10,613
  • 2
  • 18
  • 35