2011-12-20 61 views
11

我有點迷路。 我得到這個JSON:Group通過JavaScript來分組JSON數據並在optgroup上填充

[{ 
    "id": "210", 
    "name": "Name 1", 
    "category": "Category 1" 
}, { 
    "id": "187", 
    "name": "Name 2", 
    "category": "Category 1" 
}, { 
    "id": "186", 
    "name": "Name 3", 
    "category": "Category 1" 
}, { 
    "id": "185", 
    "name": "Name 4", 
    "category": "Category 1" 
}, { 
    "id": "184", 
    "name": "Name 5", 
    "category": "Category 1" 
}, { 
    "id": "183", 
    "name": "Name 6", 
    "category": "Category 1" 
}, { 
    "id": "182", 
    "name": "Name 7", 
    "category": "Category 1" 
}, { 
    "id": "181", 
    "name": "Name 8", 
    "category": "Category 2" 
}, { 
    "id": "180", 
    "name": "Name 9", 
    "category": "Category 3" 
}, { 
    "id": "178", 
    "name": "Name 10", 
    "category": "Category 2" 
}] 

而且我喜歡把所有這一切都在選擇的選項和optgroups。其實OPTGROUP應類別

我想是這樣的:

<select name="products" class="product" id="product"> 
<optgroup label="Category 1"> 
    <option value="210">Name 1</option> 
    <option value="187">Name 2</option> 
    <option value="186">Name 3</option> 
    <option value="185">Name 4</option> 
    ... 
</optgroup> 
<optgroup label="Category 2"> 
    <option value="181">Name 8</option> 
    <option value="178">Name 10</option> 
</optgroup> 
<optgroup label="Category 3"> 
    <option value="180">Name 9</option> 
</optgroup> 

今天,因爲我掙扎了太多我僅僅在此:

$(document).ready(function() { 
    $.getJSON("5.php", { 
     val: $(this).val() 
    }, function (data) { 
     $.each(data, function (i, item) { 
      $("<option/>").attr("value", item.id).append(item.name).appendTo("optgroup"); 
     }); 
    }); 
}); 

由於你可以看到沒有optgroup :) 有沒有辦法做到這一點? 我也可以修改我的JSON,如果它可以更容易。

感謝您的任何幫助。

回答

16

假設optgroups已經存在,改變了...

.appendTo("optgroup") 

這個...

.appendTo("optgroup[label='" + item.category + "']"); 

http://jsfiddle.net/FG9Lg/


如果它們不存在,你需要創建它們,儘管我會建議重構您的JSON響應以將每個項目嵌套在適當的類別。

就像這個...

{ 
    "Category 1":[ 
     {"id": "210","name": "Name 1"}, 
     {"id": "187","name": "Name 2"}, 
     {"id": "186","name": "Name 3"}, 
     {"id": "185","name": "Name 4"}, 
     {"id": "184","name": "Name 5"}, 
     {"id": "183","name": "Name 6"}, 
     {"id": "182","name": "Name 7"} 
    ], 
    "Category 2":[ 
     {"id": "181","name": "Name 8"}, 
     {"id": "178","name": "Name 10"} 
    ], 
    "Category 3": [ 
     {"id": "180","name": "Name 9"} 
    ] 
} 

所以,你可以那麼做:

var product = $('#product'); 

$.each(data, function (key, cat) { 
    var group = $('<optgroup>',{label:key}); 

    $.each(cat,function(i,item) { 
     $("<option/>",{value:item.id,text:item.name}) 
      .appendTo(group); 
    }); 

    group.appendTo(product); 
}); 

http://jsfiddle.net/FG9Lg/1/

+1

史詩的用戶名是我不得不說。 – donutdan4114 2011-12-20 16:47:20

+0

@ donutdan4114謝謝。這是要麼「看着我!看着我!」。 – 2011-12-20 16:48:59

+1

非常感謝!我修改了我的JSON並像你說的那樣完成了!它完美的工作! – user1108276 2011-12-21 10:34:00

16

如果我是你,我會用一個小型圖書館稱爲Underscore將以更簡單的表示形式返回的數據分組。

請參見下面的代碼,你也可以看到這個live demo

var groupData = _.groupBy(data, function (obj) { 
    return obj.category; 
}); 

var optGroups = []; 
for (var key in groupData) { 
    if (groupData.hasOwnProperty(key)) { 
     var optGroup = $("<optgroup></optgroup>"); 
     optGroup.attr("label", key); 
     var currentGroup = groupData[key]; 
     for (var i = 0; i < currentGroup.length; i++) { 
      $("<option />").attr("value", currentGroup[i].id).html(currentGroup[i].name).appendTo(optGroup); 
     } 
     optGroups.push(optGroup); 
    } 
} 

for(var i = 0; i < optGroups.length; i++) { 
    $("#products").append(optGroups[i]); 
} 

如果你毫不猶豫地使用下劃線庫,你可以考慮這個groupBy功能:

var groupBy = function(array, predicate) { 
    var grouped = {}; 
    for(var i = 0; i < array.length; i++) { 
     var groupKey = predicate(array[i]); 
     if (typeof(grouped[groupKey]) === "undefined") 
      grouped[groupKey] = []; 
     grouped[groupKey].push(array[i]); 
    } 

    return grouped; 
} 

用法:

var groupData = groupBy(data, function (obj) { 
    return obj.category; 
}); 
0

如果你想保持你的JSON格式,以下會回答你的問題:

//Loop through the json, get distinct category names, and append them as optgroup to the select dropdown 
var categories = []; 
$.each(data, function(index, item) { 
    if ($.inArray(item.category, categories) == -1) { 
     categories.push(item.category); 
     var optgroupId = "cat-" + item.category.replace(/\s/g, ""); 
     $('#id_of_select_dropdown').append('<optgroup id ="'+optgroupId+'"label="'+item.category+'">'); 
    } 
}); 
// append the options to their corresponding optgroups 
$.each(data.response, function(index, item) { 
    var optgroupId = "cat-" + item.category.replace(/\s/g, ""); 
    $('#'+optgroupId).append('<option>' + item.name + '</option>'); 
}); 

希望這有助於!

2

我知道這個線程很舊,但我需要類似的東西,我想出了這個。它會在需要時自動添加optgroup並使用選項填充它們。另外,它既適用於有選擇羣組的情況,也適用於不適用的情況。

http://jsfiddle.net/mzj0nuet/

var select = $('#product'); 

$.each(data, function (key, cat) { 
    var option = "<option value='"+cat.id+"'>"+cat.name+"</option>"; 

    // If we ave a category property, add this item to an optgroup 
    if (cat.hasOwnProperty("category")) { 
     var group = cat.category; 

     // If this optgroup is not already present, add it 
     if (select.find("optgroup[label='" + group + "']").length === 0) { 
      select.append("<optgroup label='" + group + "' />"); 
     } 

     select.find("optgroup[label='" + group + "']").append(option); 

    // No category, no optgroup. Add this as simple option 
    } else { 
     select.append(option); 
    }   
});