Home > Enterprise >  Default select option based on current year
Default select option based on current year

Time:02-28

I need a JS that autoselect as default option the current year from this select-dropdown. Now we are in 2022, so the defaul option must be 2022.

Thanks.

<select id="yearDP">
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2022">2023</option>
<option value="2022">2024</option>
<option value="2022">2025</option>
<option value="2022">2026</option>
</select>

CodePudding user response:

<select id="yearDP">
    <option value="2021">2021</option>
    <option value="2022">2022</option>
    <option value="2023">2023</option>
    <option value="2024">2024</option>
    <option value="2025">2025</option>
    <option value="2026">2026</option>
</select>

<script>
    const year = new Date().getFullYear()
    let selectBox = document.getElementById('yearDP')

    selectBox.value = year
</script>
  • Related