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
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.
本文标签: javascriptjQuery group elements and create select tagStack Overflow
版权声明:本文标题:javascript - jQuery group elements and create select tag - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742401034a2467887.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论