I was trying to create a form to select month and day. I want dynamically add the exact amount of days when a specific month is selected. But only the January, February, and April of months are selectable after running the switch statement. Can anyone pls help me?
html:
<select id="months" name="months"> <option value='31'> January </option> <option value='28'> February </option> <option value='31'> March </option> <option value='30'> April </option> <option value='31'> May </option> <option value='30'> June </option> <option value='31'> July </option> <option value='31'> August </option> <option value='30'> September </option> <option value='31'> October </option> <option value='30'> November </option> <option value='31'> December </option> </select> <select id="days" name="days"></select>
js:
const $months = document.getElementById('months') function dayOfMonthOne() { for (let i = 1; i < 32; i++) { const days = ` <option>${i}</option> ` const $days = document.getElementById('days') $days.innerHTML = $days.innerHTML + days } } function dayOfMonthZero() { for (let i = 1; i < 31; i++) { const days = ` <option>${i}</option> ` const $days = document.getElementById('days') $days.innerHTML = $days.innerHTML + days } } function dayOfMonthTwo() { for (let i = 1; i < 29; i++) { const days = ` <option>${i}</option> ` const $days = document.getElementById('days') $days.innerHTML = $days.innerHTML + days } } $months.addEventListener('change', function(){ switch ($months.value) { case '31': $months.value = '31' dayOfMonthOne() break case '30': $months.value = '30' dayOfMonthZero() break case '28': $months.value = '28' dayOfMonthTwo() break } })
Advertisement
Answer
It’s because you’re setting $month.value
in the switch statement. Since there are duplicate values, the first match will be selected. In the cases above, the first value for 31 is January, 28 for February, and 30 for April.
Also, in your code, you’re just concatenating the options. So when you change from one month to another, the old month’s options don’t get replaced.
You could also use just one function for this by getting the value of the month and setting that as the i < monthLengthInDays
.
Another thing to try is getting the number of days via the Date object.
new Date(year, monthOneBasedIndex, 0).getDate();
This will return the last day of the month.