<optgroup> с JSON в цикле $.each

Я пытаюсь проанализировать файл JSON таким образом, чтобы subsectors JSON показаны в <optgroup label=""> (не хочу, чтобы их можно было выбирать).

У меня есть этот файл JSON:

{
  "sectors": [
    {
      "title": "Business, Finance & Technology",
      "subsectors": [
        {
          "title": "Finance and insurance",
          "industries": [
            {"name": "Retail banking"},
            {"name": "Insurance"},
            {"name": "Investment banking"}
          ]
        },
        {
          "title": "Business Services",
          "industries": [
            {"name": "Accounting & Audit"},
            {"name": "Recruitment"},
            {"name": "Legal services"}
          ]
        }
      ]
    },
// extra code omitted for brevity

И я заселяю <select> Варианты с этим:

// populate <select> with available choices
$.getJSON('models/industries.json', function (data) {
    $.each(data.sectors, function (i, sector) {
        $.each(sector.subsectors, function (i, subsector) {
            $('<option />').html('#' + subsector.title).appendTo('.js-industries-select');

            $.each(subsector.industries, function (i, industry) {
                $('<option />').html(industry.name).appendTo('.js-industries-select');
            })
        });
    });
});

Затем я вызываю плагин Chosen, чтобы изменить <select> в динамический вход. Вы можете увидеть, какие элементы я хочу, как label быть отмеченным #,

Смотрите демо здесь: http://jsfiddle.net/qaczD/

Мне в основном нужно создать <optgroup> до последнего $.eachназначьте label="" как subsector.title а затем заполните эту группу с выбором. Когда последний $.each закончил, закройте `как-нибудь и начните новый.

Есть идеи?

2 ответа

Решение

Попробуйте это одно: http://jsfiddle.net/qaczD/2/

// populate <select> with available choices
$.getJSON('http://dl.dropboxusercontent.com/u/48552248/websites/timewasted/new/industries.json', function (data) {
    $.each(data.sectors, function (i, sector) {
        $.each(sector.subsectors, function (i, subsector) {

             var optGroup=$('<optgroup />').attr('label','#' + subsector.title).appendTo('.js-industries-select');
            $.each(subsector.industries, function (i, industry) {
                // if (industry.name.search(regex) != -1) {
                    $(optGroup).append( $('<option />').html(industry.name));
                // }
            })
        });
    });
    console.log('yes');
});

// call chosen plugin that prettifies the Industry options
setTimeout(function() {$(".js-industries-select").chosen({
  placeholder_text_multiple: 'e.g. Retail banking…'
});}, 1000);

Решение

 $.each(sector.subsectors, function (i, subsector) {
        var group = $('<optgroup />').attr('label','#' + subsector.title).appendTo('.js-industries-select');

        $.each(subsector.industries, function (i, industry) {
            $('<option />').html(industry.name).appendTo(group);
        })
    });
Другие вопросы по тегам