next 7 days in drop-down list [duplicate]

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

Answers:

Answer

Add this line to the top of your code:

var options = "";
Answer

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.