1

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.

3
  • 2
    can set value (selected) any time using $('#mySelect').val(someValue). Setting value of <select> itself is same as setting selected on the option tag Commented Dec 14, 2013 at 19:19
  • 1
    There's no need to add it to the string. Just add it to the element after you convert the string to elements, and once you know the selected value. Commented Dec 14, 2013 at 19:19
  • Amazing that didn't even cross my mind. Thank you. Commented Dec 14, 2013 at 19:34

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

You are correct, This was just for an example, but I will fix it to avoid confusion.
@HowardZoopaloopa - good for you, I've updated the answer with a solution for setting the selected option

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.