I am using jQuery 1.7.2.
I have three checkboxes each with a unique company id. When one box is checked, I want to make a list of company ids created from the boxes that are checked.
<input type='checkbox' class='Company' data-companyid='1'> 1<br>
<input type='checkbox' class='Company' data-companyid='2'> 2<br>
<input type='checkbox' class='Company' data-companyid='3'> 3<br>
// SET BY CLASS
$Company = $("input.Company");
// GET COMPANY LIST
function getCompanyList() {
var len = $Company.length;
for (i = 0; i < len; i++) {
var CompanyID = $Company[i].data("companyid");
alert(CompanyID);
}
}
$Company.change(getCompanyList);
For some reason, I am having trouble accessing the company id via the data method in the loop. I have lots of examples of my own code where I do this sort of thing, but I can’t get this one work.
What am I missing?
You’re not accumulating the individual company ID’s into any sort of data structure.
The easiest way to return an array of values from an array of (checked) elements is to use jQuery’s
.mapfunction:The
.get()call is necessary to turn the result of.map()into a plain array.See http://jsfiddle.net/alnitak/zfUXj/