0

i have a list for choosing years in drop down, how can generate list dynamically.

my code :

 <select  id="year1">
     <option value=2012>2012</option>
     <option value=2011>2011</option>
     <option value=2010>2010</option>
 </select>

i have written a script like this,

 for(i = 0; i < 6; i++)
 {  
     document.getElementById('year1').options[i] = new Option(curr_year-i+1,curr_year-i+1);
 }        

my doubt is how can give values here,( i.e < option value= "2012">2012 ) dynamically. thanks in advance. note: for me taking value in the option is important.

Vasu
  • 265
  • 1
  • 10
  • 18

4 Answers4

3

Try this

$(document).ready(function () {
    var year = 2013;
    for(i = 0; i < 6; i++){        
    $("#year1").get(0).options[$("#year1").get(0).options.length] = new Option(year, year);
        year=year+1;
    }
});

Here the year value is incremental, for reverse order use year=year-1;

And here is the working FIDDLE

nrsharma
  • 2,532
  • 3
  • 20
  • 36
0

Try using jQuery append to append options to select.Here is how you do it dynamically

var x = 2012;
for(var i=0;i<3;i++){
    $('#ddl').append($('<option></option>').val(x).html(x));
    x=x+1;
}

Here is the demo

iJade
  • 23,144
  • 56
  • 154
  • 243
0

You can archive this by using only php Just try this,

<select  id="year1">
   <?php $current_year=date("Y");
   for($i=1900;$i<=$current_year;$i++){
      <option value="<?php echo $i;?>"><?php echo $i;?></option>
   } ?>
</select>
Vinod VT
  • 6,946
  • 11
  • 51
  • 75
0

Using pure javascript

var createComboBox = function()
{
    var select = document.createElement("select"),
        year = new Date().getFullYear();

    for(var i = 0; i < 6; i++)
    {  
        var option = document.createElement("option");
        select.appendChild(option).text = year;
        select.appendChild(option).value = year;
        year += -1
    }

    document.body.appendChild(select);
}

createComboBox();

See the demo