2017-10-23 8 views
0

Ich bin eine Drop-Down-Option über jQuery mit dem Gebäude folgenden:Wie kann ich OPTGROUP zur Select-Anweisung hinzufügen?

var myOptions = { 
    var1 : 'Road', 
    var2 : 'Rail' 
}; 

var mySelect = $('#q54'); 
    $.each(myOptions, function(val, text) { 
     mySelect.append(
      $('<option></option>').val(text).html(text) 
    ); 
}); 

die Drop-Down-Gebäude, kein Problem - ich bin dann optgroup Optionen anhänge versucht - ich habe in dem folgenden Code versucht, das Hinzufügen zu wickeln Die optgroup um die Option aber keine Freude.

var i = 1; // Addition 
$.each(myOptions, function(val, text) { 
    if(i == 1){ 
     $("#q54").append('<optgroup class="optgroups" label="Team">'); 
    } 
    mySelect.append(
     $('<option></option>').val(text).html(text) 
    ); 
    if(i == 2){ 
     $("#q54").append('</optgroup>'); 
    } 
}); 

Die HTML-Ausgabe des oben ist:

<optgroup class="optgroups" label="Team"></optgroup> 
<option value="Road">Road</option> 

Die Ausgabe sollte:

<optgroup class="optgroups" label="Team"> 
    <option value="Road">Road</option> 
</optgroup> 

Jede Beratung begrüßt.

+0

http://api.jquery.com/wrapall/ – Pointy

+0

'$ ("# Q54"). Append ('')' das ist nicht richtig, 'append' tut funktioniert nicht wie das Verketten von HTML. Wenn Sie '$ (" # q54 "). append ('')' erstellen, wird das Tag als Objekt erstellt (denken Sie daran wie ein Tag mit dem Closing auch). – RRK

+0

@RejithRKrishnan - macht Sinn - dann bin ich noch ratloser, was zu tun ist! –

Antwort

1

Betrachtet man jQuery append() wie die HTML-Zeichenfolge ist das Problem, das Sie hier begegnen.

var myOptions = { 
 
    var1 : 'Road', 
 
    var2 : 'Rail' 
 
};  
 
var i = 1; // Addition 
 
var $group = $('<optgroup class="optgroups" label="Team">'); 
 
$("#q54").append($group); 
 
$.each(myOptions, function(val, text) { 
 
    $group.append($('<option></option>').val(text).html(text)); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="q54"></select>

Eine andere Lösung ist wrapAll() zu verwenden wie Zipfel vorgeschlagen.

var myOptions = { 
 
    var1 : 'Road', 
 
    var2 : 'Rail' 
 
};  
 
var i = 1; // Addition 
 
$.each(myOptions, function(val, text) { 
 
    $("#q54").append($('<option></option>').val(text).html(text)); 
 
}); 
 
$("#q54").children().wrapAll('<optgroup class="optgroups" label="Team">');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="q54"></select>

+0

Danke dafür - sehr geschätzt. Ich versuchte zu verstehen, wie das funktionieren würde, wenn sowohl Straße als auch Schiene eine "optgroup" benötigen würden. –

+0

Sollte gesagt haben, wenn Road and Rail 'seperate' optgroups benötigt. –

Verwandte Themen