I want to get today's date in JavaScript/jQuery and display all the dates in the next 8 days in the form of "yyyy-mm-dd".
The loaded version of jQuery is "1.11.2".

Source code written
var todayDate = new Date ();
var year = todayDate.getFullYear ();
var month = ('00' + (todayDate.getMonth () + 1)). slice (-2);
var day = ('00' + todayDate.getDate ()). slice (-2);
var today = year + '-' + month + '-' + day;

With this, we have successfully acquired today's date "yyyy-mm-dd".
The HTML is as follows (source 1), and I want to insert the option with JS or jQuery, and put the dates from today to 8 days into it respectively.
The current applicable process is as follows (source 2).

▼ (Source 1) HTML file

<select name = "days"></select>

▼ (Source 2) JS file

for (var elapsed = 0;elapsed<= 7;elapsed ++) {
  $('# days'). append ('<option>&option;/option>'). text (year + '-' + month + '-' + (todayDate.getDate () + elapsed));

* I know that the variable i in the for statement is usually used. Since the variable i is already used in later processing, another variable name is used for differentiation.

In the above source, the output is as follows.

<select name = "days">2018-08-36</select>

In the first place, option is not inserted, and the number +7 on day is displayed for some reason, so it seems that iterative processing is not working in the first place ...
But I don't know why it doesn't work ...

Ideal result (if today is August 29, 2018)
<select name = "days">
To those who can respond

It's been about 3 months since I studied JS/jQuery from zero.
I am a beginner and I have no knowledge yet, but I want to solve the problem as soon as possible.
I would be very happy if you could teach me your wisdom.
Thank you very much. m (__) m

  • Answer # 1

    It's only a problem of the append part.

    for (var elapsed = 0;elapsed<= 7;elapsed ++) {
      $('# days'). append ($('<option></option>'). text (year + '-' + month + '-' + (todayDate.getDate () + elapsed))) ;

    Moving sample:https://jsfiddle.net/oesufLzc/

    【[JavaScript] Date processing】
    https://qiita.com/kazu56/items/cca24cfdca4553269cab#Addition and subtraction of dates

    [[Introduction to JavaScript] Date addition/subtraction method summary (month straddle/leap year) | Sakai Engineer School Blog | Learning Information Site for Programming Introductors https://www.sejuku.net/blog/22925

    【Use Moment.js】

Related articles