Sandra Schlichting
Sandra Schlichting

Reputation: 25986

How to insert HTML with JavaScript or JQuery?

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:

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?

Upvotes: 2

Views: 217

Answers (3)

Utilitron
Utilitron

Reputation: 402

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

Upvotes: 0

Icarus
Icarus

Reputation: 63956

How about something like this:

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

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

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
}

Upvotes: 3

Related Questions