admin管理员组

文章数量:1336200

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>
</select>

How would you approach that?

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>
</select>

How would you approach that?

Share edited Mar 19, 2011 at 22:21 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Mar 19, 2011 at 22:09 tsigertsiger 1,6472 gold badges15 silver badges16 bronze badges 5
  • Have you tried anything? – BoltClock Commented Mar 19, 2011 at 22:10
  • IKR? They just ask us to write their code. – mattsven Commented Mar 19, 2011 at 22:14
  • No i didn't try anything and i could be more than happy even with the first paragraph of BoltClock. – tsiger Commented Mar 19, 2011 at 22:38
  • @tsiger: Oh, no problem. Like I said, I provided the code only because I felt like it :) Glad I helped, been a long day for me now... – BoltClock Commented Mar 19, 2011 at 22:39
  • Thanx man :) hope you will get some rest :) I guess the downvote was for not providing something as a base. – tsiger Commented Mar 19, 2011 at 22:41
Add a ment  | 

2 Answers 2

Reset to default 6

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.

本文标签: javascriptjQuery group elements and create select tagStack Overflow