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
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/
date = new Date($('#date-input').val()) date.getDate() ...
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/