最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get checkbox value of items within div - Stack Overflow

programmeradmin4浏览0评论

I have a list checkbox's within a div which is not a form.

  <div id="priceTree">
  <div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_1"> Small </span><span class="right">5.00</span><span class="center">&nbsp;</span></div>
  <div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_2"> Medium </span><span class="right">10.00</span><span class="center">&nbsp;</span></div>
  <div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_3"> Large </span><span class="right">15.00</span><span class="center">&nbsp;</span></div>
  </div>

This list has injected elements so may not always have 3. How would I go about getting the id for only the checked checkboxs?

I have a list checkbox's within a div which is not a form.

  <div id="priceTree">
  <div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_1"> Small </span><span class="right">5.00</span><span class="center">&nbsp;</span></div>
  <div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_2"> Medium </span><span class="right">10.00</span><span class="center">&nbsp;</span></div>
  <div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_3"> Large </span><span class="right">15.00</span><span class="center">&nbsp;</span></div>
  </div>

This list has injected elements so may not always have 3. How would I go about getting the id for only the checked checkboxs?

Share Improve this question asked Apr 18, 2014 at 8:08 maxummaxum 2,9154 gold badges36 silver badges49 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

Here is a vanilla JavaScript solution:

var checkedCbs = document.querySelectorAll('#priceTree input[type="checkbox"]:checked');
var ids = [];
for (var i = 0; i < checkedCbs.length; i++) ids.push(checkedCbs[i].id);
//return ids;

Demo

Try this

$("#priceTree input:checked").each(function(){
   console.log(this.id); 
});

Demo

If you want an array of checked elements' ids, use:

var result = $('#priceTree input:checked').map(function() {
  return this.id;
}).get();

THE WORKING DEMO.

$('input[type=checkbox]:checked').attr('id');

To iterate over all checkboxes use each:

$('input[type=checkbox]:checked').each(function(){
       console.log($(this).attr('id'));
    });

Or,

$('#priceTree :checked').each(function(){
           console.log($(this).attr('id'));
        });

To get ids of all checkboxes checked within #priceTree div:

$('#priceTree input:checked').each(function(){
   alert($(this).attr('id'));
})
发布评论

评论列表(0)

  1. 暂无评论