Populate Select With OptGroup from two separate JSon jQuery objects

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 refers to the type .Id

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

 <SELECT> <OPTGROUP LABEL="type.Name" id="type.Id"> <OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION> </OPTGROUP> </SELECT> 
+4
source share
2 answers

The code below uses only β€œselect” as the jquery selector, so it will affect all selected cells on the page. You might want to change this.

The code below also does not handle one of the selected options, which you probably should follow.

 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('')); 
+2
source

Adding optgroups groups for dynamic selection using javascript

You can criate dinamamicaly combos. Access. The json values ​​are in this question.

How to access a Json object with space in its name?

Take a few situations in the messages to solve your question.

0
source

Source: https://habr.com/ru/post/1403380/


All Articles