using jQuery Using HTML input type="date" and submit button. I would like to populate the d...">

How to extract values ​​from HTML <input type = "date"> using jQuery

Using HTML input type="date" and submit button. I would like to populate the day , month and year variables with the appropriate values ​​from the date input.

 <input type="date" id="date-input" required /> <button id="submit">Submit</button> 

and jQuery:

 var day, month, year; $('#submit').on('click', function(){ day = $('#date-input').getDate(); month = $('#date-input').getMonth() + 1; year = $('#date-input').getFullYear(); alert(day, month, year); }); 

Here's a sample code: https://jsfiddle.net/dkxy46ha/

a console error tells me that .getDate() not a function.

I saw similar questions, but the solutions didn't work for me. How can I extract day, month and year from input type="date" ? Thanks

+7
javascript jquery date html
source share
3 answers

First you need to create a Date object from the value of the input element. And then you can get the day, month and year from this object.

 $('#submit').on('click', function(){ var date = new Date($('#date-input').val()); day = date.getDate(); month = date.getMonth() + 1; year = date.getFullYear(); alert([day, month, year].join('/')); }); 

Working example: https://jsfiddle.net/8poLtqvp/

+9
source share
 date = new Date($('#date-input').val()) date.getDate() 

...

+2
source share

The date value returned by input type="date" is the format yyyy-mm-dd . May use .split() with the argument "-" to retrieve an array containing [yyyy, mm, dd]

Note. alert() expects a string as a parameter; does not print values, the same as console.log() with a comma operator ,

 var day, month, year; $('#submit').on('click', function() { var date = $('#date-input').val().split("-"); console.log(date, $('#date-input').val()) day = date[2]; month = date[1]; year = date[0]; alert(day + month + year); }); 

jsfiddle https://jsfiddle.net/dkxy46ha/2/

+2
source share

All Articles