slandau
slandau

Reputation: 24052

Loop through checkboxes and gather names of the ones that are checked - JQuery

<input type="checkbox" name="SummaryInformation">Summary Information<br />
                        <input type="checkbox" name="ProductLegs">Product Legs<br />
                        <input type="checkbox" name="AmortizationOptions">Amortization Options<br />
                        <input type="checkbox" name="Values">Values<br />
                        <input type="checkbox" name="Rates">Rates<br />
                        <input type="checkbox" name="RatesSpecific">Rates (All-In-Rate, PV01)<br />
                        <input type="checkbox" name="AmortizationSchedule">Amortization Schedule<br />
                        <input type="checkbox" name="SponsorInfo">Sponsor/Affiliate Info<br />
                        <input type="checkbox" name="BorrowerInfo">Borrower Info<br />
                        <input type="checkbox" name="SponsorContacts">Sponsor/Affiliate Contacts<br />
                        <input type="checkbox" name="CashFlows">Cash Flows<br />
                        <input type="checkbox" name="PrePayment">Pre-Payment<br />
                        <input type="checkbox" name="FutureExposure">Potential Future Exposure<br />
                        <input type="checkbox" name="FutureExposureSpecific">Potential Future Exposure (Max Number and Date Only)<br />
                        <input type="checkbox" name="History">History<br />

I need to loop through all of these in JQuery and create an array of the names of the ones that are checked. How would I do this?

Upvotes: 2

Views: 1553

Answers (5)

Hussein
Hussein

Reputation: 42808

Use filter it's faster.

$('input').filter(function() {return this.checked})

Upvotes: 0

Dutchie432
Dutchie432

Reputation: 29160

It's as simple as

$("input:checked").each(...);

Here is a Live Demo: http://jsfiddle.net/vFmNh/3/

Upvotes: 0

Shlomi Komemi
Shlomi Komemi

Reputation: 5545

var arr = [];

$('input[type=checkbox]').is(':checked').each(function(){
     arr.push($(this).attr('name'));
});

alert(arr.join('-'));

Upvotes: 1

coreyward
coreyward

Reputation: 80041

Use the checked selector:

$(':checked').each(function(){
  ...
});

Upvotes: 0

mkoryak
mkoryak

Reputation: 57928

var names = [];
$("checkbox:checked").each(function(){
   names.push($(this).attr("name"));
})

you might want to add a div around the checkboxes you want this done to, so that you dont loop through ALL checkboxes on the screen.

if you did this the selector would change to:

$("#mydiv checkbox:checked")

where mydiv is the id of that div

Upvotes: 4

Related Questions