下拉列表中的下一个7天

时间:2015-10-01 15:07:04

标签: javascript html html-select

我希望接下来的7天会出现在下拉列表中。但是我的代码似乎不起作用。

请注意,日期格式必须为yyyy-mm-dd

你能帮我吗?这是我的代码:



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>");
&#13;
<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>
&#13;
&#13;
&#13;

fiddle

3 个答案:

答案 0 :(得分:1)

以这种方式初始化options = "";

<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>

答案 1 :(得分:0)

将此行添加到代码顶部:

var options = "";

答案 2 :(得分:0)

您需要添加

var options = "";
在for循环上方

,然后删除

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

(否则选项全部被覆盖)。

See this fiddle for a working version