Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add option value of the select box dynamically using javascript

Tags:

javascript

I want to populate the year in a select javascript. I did the following code.

<html>
<head>
    <script type="text/javascript">         
        $(document).ready(function(){   
            var cur_year=new Date().getFullYear();
            var obj=document.getElementById("yr");  
            alert(obj);         
            for (var i = 2000; i <= 2020; i++)     {                
                opt = document.createElement("option");
                opt.appendChild(document.createTextNode(value));
                opt.selected = selected;
                opt.value = i;
                opt.text=i;
                obj.appendChild(opt);
            }
        });
    </script>
</head>
<body>
    <select id="yr">
<option>year</option>
</select>
</body>
</html>

I don't know what is wrong in this. I want to populate the year and want to select the current year in the select box when the user opens the browser. Any one can help? please!

like image 414
ijarlax Avatar asked Feb 12 '13 07:02

ijarlax


1 Answers

$(document).ready( function() { 
            var cur_year=new Date().getFullYear();
            var obj=document.getElementById("yr");         
            for (var i = 2000; i <= 2020; i++)     {                
                opt = document.createElement("option");
                opt.value = i;
                opt.text=i;
                obj.appendChild(opt);
            }
            document.getElementById("yr").value = cur_year;
        });
  1. Just Use .value and assign cur_year to it.

Working Fiddle

like image 143
Muhammad Talha Akbar Avatar answered Oct 05 '22 12:10

Muhammad Talha Akbar