How to create a dynamic year in dropdown using javascript
In this tutorial, we will learn How to a create dynamic year in dropdown using javascript. Here, I will explain with an example of How to a create dynamic year in the dropdown. Example: HTML SELECT element using JavaScript.
First, we use the window.onload
event handler and the dropdown list i.e. HTML SELECT element will be referenced and using a For Loop, and get one by one Year values will be appended to the DropDownList.
How to a create dynamic year in dropdown using javascript
Example
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>How to a create dynamic year in dropdown using javascript</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body style="text-align: center;">
<h1>How to a create dynamic year in dropdown using javascript</h1>
<select id="years"></select>
<script type="text/javascript">
window.onload = function () {
//The DropDownList.
var years = document.getElementById("years");
//Get the Current Year.
var currentYear = (new Date()).getFullYear();
//Loop and add the Year to DropDownList.
for (var i = 1970; i <= currentYear; i++) {
var option = document.createElement("OPTION");
option.innerHTML = i;
option.value = i;
years.appendChild(option);
}
};
</script>
</body>
</html>