使用OptGroup从两个分离的JSon对象JQuery填充Select

Populate Select With OptGroup From Two Seperate JSon Objects JQuery

本文关键字:JSon 对象 JQuery Select 填充 分离 两个 OptGroup 使用      更新时间:2023-09-26

我有两个json对象

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

subType.ParentId引用该类型。Id

我希望能够在jQuery中填充一个具有的select

<SELECT> 
<OPTGROUP LABEL="type.Name" id="type.Id">        
<OPTION LABEL="subType.Name" value="subType.Id">subType.Name</OPTION>                  
</OPTGROUP>
</SELECT>

下面的代码只使用"select"作为jquery选择器,因此它将影响页面上的所有选择框。你可能想改变这一点。

下面的代码也不处理选择其中一个选项的问题,这可能是您应该注意的问题。

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

添加optgroup以使用javascript动态进行选择

你可以经常喊组合。访问json的值在这个问题中。

如何访问名称中有空格的Json对象?

在帖子中列出一些情况来解决您的问题。