Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

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

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

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

and the 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 code sample: https://jsfiddle.net/dkxy46ha/

the console error is telling me that .getDate() is not a function.

I have seen similar questions but the solutions have not worked for me. How can I extract the day, month and year from the input type="date"? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Firstly you need to create a Date object from input element value. And then you will be able to get day, month and year from this object.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...