snert
snert

Reputation: 15

jQuery looping checkboxes

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")););

Upvotes: 0

Views: 65

Answers (2)

Manikant Gautam
Manikant Gautam

Reputation: 3581

You can get all those are selected followed by Join.The get() method returns a specified element from a Map object.

console.log($('input:checkbox[id^="pdfam_"]:checked').map(function() {
   return this.id || null;
}).get().join(','))
<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 />

Upvotes: 0

user8897421
user8897421

Reputation:

A simple way is to use .map() to make an array of the IDs, then use .toArray().join(", ") to get your string.

var s = $('input:checkbox[id^="pdfam_"]:checked')
  .map(function(i, el) { return el.id })
  .toArray()
  .join(", ");
  
console.log(s);
<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 />

Upvotes: 2

Related Questions