next 7 days in drop-down list [duplicate]

2019-03-02 17:12发布

问题:

This question already has an answer here:

  • How to get next seven days from X and format in JS 6 answers

I'd like the next 7 days to appear in a drop-down list. However my code doesn't seem to work.

Please note that the date format has to be yyyy-mm-dd.

Could you please help me. Here is my code:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
var curr = new Date;
var first = curr.getDate()
var firstday = (new Date(curr.setDate(first))).toString();
for (var i = 0; i < 7; i++) {
    var next = new Date(curr.getTime());
    next.setDate(first + i);
    options += '<option>' + formatDate((next.toString())) + '</option>';
}

$("#datemenu1").append(options);
$("#datemenu1").html("<option>PICK A DATE</option>");
<html>

<select id="datemenu1">
  
  <option>PICK A DATE</option>
  
</select>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="Text-1.js"></script>strong text
</html>

fiddle

回答1:

Add this line to the top of your code:

var options = "";


回答2:

Initialise options = ""; this way:

<html>
    <body>
        <select id="datemenu1">

            <option>PICK A DATE</option>

        </select>
        <script src="http://code.jquery.com/jquery.min.js"></script>
        <script src="Text-1.js"></script>strong text
        <script>
            function formatDate(date) {
                var d = new Date(date),
                        month = '' + (d.getMonth() + 1),
                        day = '' + d.getDate(),
                        year = d.getFullYear();

                if (month.length < 2)
                    month = '0' + month;
                if (day.length < 2)
                    day = '0' + day;

                return [year, month, day].join('-');
            }

            var options = "";
            var curr = new Date;
            var first = curr.getDate()
            var firstday = (new Date(curr.setDate(first))).toString();
            for (var i = 0; i < 7; i++) {
                var next = new Date(curr.getTime());
                next.setDate(first + i);
                options += '<option>' + formatDate((next.toString())) + '</option>';
                $("#datemenu1").append(options);
            }


        </script>
    </body>
</html>


回答3:

You need to add

var options = "";

above the for loop, and remove

$("#datemenu1").html("<option>PICK A DATE</option>");

(otherwise the options are all overwritten).

See this fiddle for a working version