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.

0

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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>

5 Comments

give same instance in jsp ?
@user2773010 by using jsp you can just replace the variables and displaying of variables
you we cant do in jsp ?
<select id="year1"> int current_year=2013; for(int i=1900;int i<=current_year;int i++){ <option value=+"i"+>+i+</option> } </select>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.