Sush
Sush

Reputation: 1457

generate <optGroupTag> from a json

i have a josn data like this

{ name: [ 'a', 'b' ], property: [ 'art', 'test' ] }

From this how can i create an <optgroupTag> with lables name ,property name values a,b,c property values art,test

<select>
  <optgroup label="name">
    <option value="a">a</option>
    <option value="b">b</option>
  </optgroup>
  <optgroup label="property">
    <option value="art">art</option>
    <option value="test">test</option>
  </optgroup>
</select> 

Upvotes: 1

Views: 22

Answers (1)

Satpal
Satpal

Reputation: 133453

You can try this. Basically You have to iterate you JSON

var data = {
    name: ['a', 'b'],
    property: ['art', 'test']
};
var html = '';
for (var item in data) {
    html += '<optgroup label="' + item + '">';
    $.each(data[item], function (innerItem, index) {
        html += '<option value="' + innerItem+ '">' + innerItem+ '</option>';
    })
    html += '</optgroup>'
}
$('select').html(html);

DEMO

var data = {
    name: ['a', 'b'],
    property: ['art', 'test']
};
var html = '';
for (var item in data) {
    html += '<optgroup label="' + item + '">';
    $.each(data[item], function (index, value) {
        html += '<option value="' + value + '">' + value + '</option>';
    })
    html += '</optgroup>'
}
$('select').html(html);

DEMO 2

Upvotes: 1

Related Questions