user3441287
user3441287

Reputation: 21

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, e.g. 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?

Upvotes: 0

Views: 3778

Answers (6)

H77
H77

Reputation: 5967

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' />

Upvotes: 2

LostKatana
LostKatana

Reputation: 506

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.

Upvotes: 0

Jamie Barker
Jamie Barker

Reputation: 8256

var date = new Date();
var year = date.getFullYear(); 

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

FiDDLE

Upvotes: 0

Gwenc37
Gwenc37

Reputation: 2048

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>;

Upvotes: 0

Makla
Makla

Reputation: 10459

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);
}

Upvotes: 0

A J
A J

Reputation: 2140

This is one way of doing it .. fiddle

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

append option according to your logic.

Upvotes: 0

Related Questions