简体   繁体   中英

Dynamically add options to select select tag

I am trying to write a select drop down which is dynamically filled up with options, the options are the years, eg 2010, 2011, 2012

But with each coming year the webpage should add new entry in the drop down with the current year. The first entry of the year is 2010 fixed but the last entry is dynamic and depends on the current year..

Any help?

Something like this?

 var currentYear = new Date().getFullYear(); for (var i = 2010; i <= currentYear; i++) { var selected = ''; if (i == currentYear) selected = 'selected'; $("#years").append("<option value='" + i + "'" + selected + ">" + i + "</option>") } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='years' /> 

Why don't you select the current year substract 2010 from it ( because it is a fix end) and then you will count up from 2010 adding the amount from your result? Thats how I would do that with the first thoughts.

Edit: If you fill the dropdown on each load of the page you always fill that array with the amount calculated from your substraction. I don't get the problem.

This is one way of doing it .. fiddle

 $("select").append("<option value='added'>added</option>");

append option according to your logic.

Here is the jsfiddle link (without jquery).

<form>
<select id="mySelect">
</select>
</form>

Javascript:

var x = document.getElementById("mySelect");
var to = new Date().getFullYear();
var option;
for (var i = 2010; i <= to; i++)
{
    option = document.createElement("option");
    option.text = i;
    x.add(option);
}

Just use the actual date :

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

And then you can generate your select options

var select = '<select>';
for (var i = startYear; i <= currentYear; i++){
     select += '<option>'+i+'</option>';
}
select += </select>;
var date = new Date();
var year = date.getFullYear(); 

for (var i=2010;i<year+1;i++) {
   $('#MySelect').append('<option value="'+i+'">'+i+'</option>')
}

FiDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM