2012-03-26 9 views
4

Ich habe zwei JSON-ObjektePopulate Select Mit optgroup Von zwei Seperate JSon Objekte JQuery

var type = [{"Id":1,"Name":"This is a name"}]; 
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"},]; 

subType.ParentId verweist die type.Id

Ich möchte

eine Auswahl füllen können, in jQuery mit
<SELECT> 
<OPTGROUP LABEL="type.Name" id="type.Id">   
<OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION>     
</OPTGROUP> 
</SELECT> 

Antwort

2

Der folgende Code verwendet nur "Auswählen" als JQuery-Selektor, so dass alle Selectedboxes auf der Seite betroffen sind. Sie möchten das wahrscheinlich ändern.

Der unten stehende Code behandelt auch nicht die Auswahl einer der Optionen, auf die Sie achten sollten.

var type = [{"Id":1,"Name":"This is a name"}]; 
var subType = [{"Id":2,"ParentId":1,"Name":"This is a name"}]; 

var output = []; 
$.each(type, function(){ 
    //for each type add an optgroup 
    output.push('<optgroup label="'+this.Name+'">'); 
    var curId = this.Id; 

    //linear search subTypes array for matching ParentId 
    $.each(subType, function(k,v){ 
     if(this.ParentId = curId){ 

     output.push('<option label="'+this.Name +'" value="'+ this.Id +'">'+ this.Name +'</option>'); 

     //DELETE the element from subType array so the next search takes less time 
     subType.splice(k,1); 
    } 
    }); 
    output.push('</optgroup>'); 
}); 

//change the 'select' here to the id of your selectbox 
$('select').html(output.join('')); 
+0

Ich benutzte deine Methode und es funktioniert teilweise, aber kannst du mir sagen, was mit http://jsfiddle.net/kvkxX/ falsch ist? –

+0

Das Format Ihres Subtyps wurde geändert. Es gab einige extra "[]" http://jsfiddle.net/kvkxX/1/ –

+0

Danke, funktioniert gut! :) –