Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Adding Options

I have the following html structure and am trying to add in option elements in the optgroups via javascript. I am using the jquery mobile framework as well.

Html as follows:

<form>
    <div class="ui-field-contain">
    <label for="selectID">Look-up</label>
    <select name="select-native-4" id="selectID">
       <option>Choose...</option>

           <optgroup label="G1" id="group1">                              
           </optgroup>
           <optgroup label="G2" id="group2">
           </optgroup>
           <optgroup label="G3" id="group3">
           </optgroup>

           </select>
       </div>
  </form>

The javascript is as follows.

for( var i = 0; i < array.length; i++){
        var item = array[i];
        var $option = $('<option> ' + item.name + ' </option>');
        $option.prop('value', item.memb);
        console.log(item.name);
        var tp = -1;
        switch(item.name){
            case 'group1' :
                tp = 1;   break;
            case 'group2' :
                tp = 2;   break;
            case 'group3' :
                tp = 3;   break;
        }
        console.log(tp);
        //$("#selectID :nth-child(tp)").append($option);

        $("#selectID").eq(tp).append($option);
    }
    $('#selectID').selectmenu('refresh');
}

I am confused as to why the .eq(n) does not append the $option object to the nth child of #selectID, which would be an optgroup. Thanks for any help!

like image 905
randydalton411 Avatar asked Feb 13 '26 15:02

randydalton411


1 Answers

You only have 1 #selectID. You need:

$('#selectID optgroup').eq(tp).append($option);

This will hit the optgroups inside your select id.

like image 90
StaticVoid Avatar answered Feb 15 '26 04:02

StaticVoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!