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
2 Answers
Reset to default 6Well, 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742401035a4436915.html
评论列表(0条)