【问题标题】:Populate Select With OptGroup From Two Seperate JSon Objects JQuery使用来自两个单独的 JSon 对象 JQuery 的 OptGroup 填充选择
【发布时间】:2012-04-09 14:10:10
【问题描述】:

我有两个 json 对象

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

subType.ParentId 引用 type.Id

我希望能够在 jQuery 中填充一个选择

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

【问题讨论】:

    标签: javascript jquery json select optgroup


    【解决方案1】:

    下面的代码仅使用“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(''));
    

    【讨论】:

    【解决方案2】:

    Adding optgroups to select using javascript dynamically

    您可以创建动态组合。访问 json 的值在这个问题中。

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

    在帖子中有一些情况可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2012-10-09
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多