next 7 days in drop-down list [duplicate]

2019-03-02 16:44发布

This question already has an answer here:

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

3条回答
小情绪 Triste *
2楼-- · 2019-03-02 17:03

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楼-- · 2019-03-02 17:05

Add this line to the top of your code:

var options = "";
查看更多
霸刀☆藐视天下
4楼-- · 2019-03-02 17:11

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

查看更多
登录 后发表回答