1

I'm having trouble figuring out how to get the correct number of days in a given month to populate in a dropdown, based on a previously selected month in a different dropdown. I already have the JavaScript setup to populate the month dropdown, but I can't figure out how to use that data to get the days correct. I was thinking I should use if-else statements and for loops for each statement based on the selected month's value, but cannot figure out how to link the two.

Here's the related HTML:

<div class="form-group">
    <label for="monthDrop">Birthday :</label>
    <div class="form-row">
        <div class="form-group col-3">
            <select class="form-control form-control-sm" id="monthDrop">
            </select>
        </div>
        <div class="form-group col-3">
            <select class="form-control form-control-sm" id="dayDrop">
            </select>
        </div>
        <div class="form-group col-4">
            <select class="form-control form-control-sm" id="yearDrop">
            </select>
        </div>
    </div>
</div>

And here's the JavaScript I've done so far:

var month = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "June",
    "July",
    "Aug",
    "Sept",
    "Oct",
    "Nov",
    "Dec"
];

var html;

function print(message, id) {
    var id = document.getElementById(id);
    id.innerHTML = message;
}

function printMonthOptions(option) {
    var newMonthArray = [];
    for (var i = 0; i < option.length; i += 1) {
        var optionHTML = `<option value="`;
        optionHTML += option.indexOf(option[i]) + 1;
        optionHTML += `">`;
        optionHTML += option[i];
        optionHTML += `</option>`;
        newMonthArray.push(optionHTML);
    }
    return newMonthArray.join('');
}

html = printMonthOptions(month);
print(html, 'monthDrop');

I'm fairly new to JavaScript, all of my knowledge is from teamtreehouse, but I'm really trying to learn. I'm also sure there's an easier way to do all of this so any advice about how I've put this together and how to fix it would be much appreciated.

Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74
  • Does this answer your question? [What is the best way to determine the number of days in a month with JavaScript?](https://stackoverflow.com/questions/315760/what-is-the-best-way-to-determine-the-number-of-days-in-a-month-with-javascript) – Tracer69 Feb 15 '20 at 20:32

0 Answers0