Best and Easiest Dynamic Year Dropdown using Javascript

 There are many ways to show Year Dropdown on  your page.

1. To hard code the years 

                        <option value="2021">2021</option>

                        <option value="2020">2020</option>

                        <option value="2019">2019</option>

                        <option value="2018">2018</option>

                        <option value="2018">2018</option>

This is not the right approach as code has to be updated after change in year.

2. Adding Year from Database.

This will include creating table showing the years and then writing a query in your code to show the years.

This approach also has limitations as the data has to be updated every year in your table. 


Best Way - The best way is totally automatic which does not include any human intervention after creation of code. 

Javascript Code:

<script type="text/javascript">

                    window.onload = function () {                       

                        var years = document.getElementById("years");                     

                        var currentYear = (new Date()).getFullYear();

                        for (var i = 2021; i <= currentYear; i++) {

                           var option = document.createElement("OPTION");

                            option.innerHTML = i;

                            option.value = i;

                            years.appendChild(option);

                        }

                    };

                </script>

HTML Code:

                    <select name="years" id="years">

                        <option value=""></option>

                        

                        </select>

Add the above code and the dropdown looks like 






Toggle the loop in javascript and the dropdown start from that year itself

Like if you have to tale year of birth, change the javascript 

for (var i = 1950; i <= currentYear; i++) {

the dropdown will be 










Hope this helps.

Comments

Popular posts from this blog

The Time has Come

I still shiver

Best way to dispense water from 20L bottle | India 2020