开发者

jQuery group elements and create select tag

Ok here's what i have

<div>
 <h2 class="type">A</h2>
 <p class="value">12</p>
</div>

<div>
 <h2 class="type">A</h2>
 <p class="value">24</p>
</div>

<div>
 <h2 class="type">B</h2>
 <p class="value">35</p>
</div>

And what i want to do is go through them, group them and create a select dropdown like this:

<select>
 <option value="12,24">A</option>
 <option value="35">B</option>
&开发者_运维百科lt;/select>

How would you approach that?


Well, I felt like writing some jQuery code tonight for kicks before I go to bed.

Basically, iterate through your <div>s and make an object of arrays out of their types and values. After that, make a <select>, iterate through the object and add dropdown <option>s containing its types and values.

var types = {};

$('div').each(function() {
    var type = $('.type', this).text();
    var value = $('.value', this).text();
    if (!types[type]) types[type] = [];

    types[type].push(value);
});

var select = $('<select></select>');

$.each(types, function(i, v) {
    select.append('<option value="' + v + '">' + i + '</option>');
});

select.appendTo('body');

jsFiddle demo


Something like:

var options;

$("p.type").each(function(i, el){
    el = $(el);
    var value = el.siblings("p.value").text();

    if(options[el.text()] == null){
        options[el.text()] = [value];
    } else { options[el.text()].push(value); }
});

Now you have the them in options for easy manipulation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜