0

I have a select dropdown that is dynamically populated like this:

var year = (new Date()).getFullYear(); var minYear = year-95; var options = []; for(var i=minYear; i < year+1; i++){ options.push('<option value="'+i+'">'+i+'</option>'); } 

How can I set a selected option?

1
  • When i == year then select option? Commented Jan 15, 2015 at 12:43

2 Answers 2

1

Add selected to the option (more info about option selected).

Your code should look like this:

var year = (new Date()).getFullYear(); var minYear = year-95; var options = []; for(var i = minYear; i < year + 1; i++) { if (i == year) // Condition for selected option { options.push('<option selected value="' + i + '">' + i + '</option>'); } else { options.push('<option value="' + i + '">' + i + '</option>'); } } 
Sign up to request clarification or add additional context in comments.

4 Comments

Very much appreciated. Thank you! Do you happen to know a way to focus on that selected option once the dropdown is expanded?
It should be focused.
I've added a jQuery library for styling that select dropdown which makes a ul with the options and hides the select. So the option is not focused when expanded.
Ok. It depends on the library. But that is another question.
1

Try something like this

jQuery

$(document).ready(function () { var year = (new Date()).getFullYear(); var minYear = year - 95; var options = []; for (var i = minYear; i < year + 1; i++) { if (i == 1950) { options.push('<option selected value="' + i + '">' + i + '</option>'); } else { options.push('<option value="' + i + '">' + i + '</option>'); } } $("#sel").html(options); }); 

HTML

<select id="sel"></select> 

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.