Reputation: 3822
I've got a loop building an option set that I fill up an empty node with using jQuery.
i.e;
var optList = function(){
var list;
for(i=0;i<5;i++){
list += '<option>'+i+'</option';
}
return optList;
}
$('#mySelect').html(optList());
My question is, given my output string from optList
is there a way of having adding "selected"
to a predetermined value? like: <option selected>4</option>
using my string? I'm asking because I build my optList BEFORE I am aware of what that predetermined value will be.
Upvotes: 1
Views: 361
Reputation: 318162
You can't return the function, you have to return the list
var optList = function(selected_value){
var list;
for(var i=0; i<5; i++){
var selected = i == selected ? ' selected="selected"' : '';
list += '<option value="+i+" '+selected+'>'+i+'</option';
}
return list;
}
$('#mySelect').html(optList(4));
Or you could use what you have and just do
$('#mySelect').html(optList()).val(4);
Upvotes: 1