jQuery looping checkboxes

时间:2017-12-08 15:37:51

标签: javascript jquery

I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.

When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.

The HTML looks like this:

<input type="checkbox" id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />

There are about 40 of these checkboxes. What I'm looking for is a string like:

"pdfam_711131, pdfam_711341"

I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.

$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););

2 个答案:

答案 0 :(得分:2)

一种简单的方法是使用.map()制作ID数组,然后使用.toArray().join(", ")获取字符串。

&#13;
&#13;
var s = $('input:checkbox[id^="pdfam_"]:checked')
  .map(function(i, el) { return el.id })
  .toArray()
  .join(", ");
  
console.log(s);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以选择所有选中的Joinget() method返回Map对象中的指定元素。

&#13;
&#13;
console.log($('input:checkbox[id^="pdfam_"]:checked').map(function() {
   return this.id || null;
}).get().join(','))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
&#13;
&#13;
&#13;

相关问题