Reputation: 117
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!
Upvotes: 3
Views: 127
Reputation: 2745
Your code is appending to the Select
object not the optgroup
.
.eq(index)
gives you an object at that index that matches the selector. In this case there is only one select so you're away going to get it.
Here's how I would handle this example.
I would write the $option
definition line like this.
var $option = '<option> ' + item.name + ' </option>';
In place of the switch
statement I'd put this.
$("#"+item.name).append($option);
ID's should be unique for the entire HTML page so this should be the only group with that ID. That being the case you can add it directly to that optgroup
Upvotes: 0
Reputation: 1537
You only have 1 #selectID. You need:
$('#selectID optgroup').eq(tp).append($option);
This will hit the optgroups inside your select id.
Upvotes: 1