4

I have two json objects

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

subType.ParentId references the type.Id

I want to be able to populate a select in jQuery having

<SELECT> 
<OPTGROUP LABEL="type.Name" id="type.Id">        
<OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION>                  
</OPTGROUP>
</SELECT>
Rami Sakr
  • 556
  • 1
  • 6
  • 14

2 Answers2

2

The code below uses just "select" as a jquery selector, so it will affect all selectboxes on the page. You probably want to change this.

The code below also does not handle having one of the options selected which is probably something you should watch out for.

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

Adding optgroups to select using javascript dynamically

You able criate dinamamicaly the combo. Access The values of json is In this question.

How to access Json Object which has space in its name?

Have some situations in posts to resolve your question.

Community
  • 1
  • 1
Jones
  • 1,480
  • 19
  • 34