2

I would like to be able to insert a dropdown box where I have specified with option that should be selected as default.

Something like the code below, where the first should insert a dropdown box with default selected "BBB" (val2 ~ BBB).

This JSFiddle almost does what I need, but the problem with it is:

  • it should be possible to define which option should be selected as default
  • the JavaScript/JQuery should be generic and not hardcoded to a specific ID

What I would like is something like this

<select>
    <script type='text/javascript'>
        insert_dropdown("val2");
    </script>
</select>

<select>
    <script type='text/javascript'>
        insert_dropdown("val3");
    </script>
</select>

How should such a function be made?

1
  • I posted a data driven approach to setting a default selected value. If you get a chance, check it out. Commented Aug 2, 2011 at 15:21

3 Answers 3

3

Try this

//Assuming options is an array of code/value pair
    insert_dropdown(options, default, $("#select1"));

function insert_dropdown(options, default, container){
  $.each(options, function(){
    container.append("<option value='"+this.code+"'>"+this.value+"</option>");
  });
  container.val(default);//This will select the default option
}
Sign up to request clarification or add additional context in comments.

1 Comment

It looks very impressive! How should I implement it? jsfiddle.net/littlesandra88/UWPCJ Can't quite figure it out.
0

How about something like this:

function setDefaultValue(theValue)
{ $('#myselect').val(theValue);}

3 Comments

Would I be able to call this from within a pair of <select><script type='text/javascript'>?
@Sandra Schlichting, no, you can't execute javascript code within <select> elements since you can't attach eventhandlers to those elements. I'm sure there are ways to accomplish what you need but I don't think we have enough info to advise as to what's the best approach.
If what you need is set the default value on another select element based on some selection on another select list, you can handle the onchange event and set the default value that way.
0

Try this: In order to make an option selected you need to set selected = true, so we make an object of objects that holds a selected value that will ultimately set it's self as selected.

$(document).ready(function(){
    var myOptions = {
        "option1":{"text":'AAA',"value":'val1',"selected":false},
        "option2":{"text":'BBB',"value":'val2',"selected":true},
        "option3":{"text":'CCC',"value":'val3',"selected":false}
    };

    for (i in myOptions){
        var myOption = myOptions[i];
        var option = new Option(myOption ['text'],myOption ['value']);
            option.selected = myOption ['selected'];
        $('#mySelect').append(option);
    };

});

JSFiddle

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.