1

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?

http://jsfiddle.net/Msc95/

Evik James
  • 10,335
  • 18
  • 71
  • 122

2 Answers2

2

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 .map function:

function getCompanyList() {
    var companyList = $Company.filter(':checked').map(function() {
       return $(this).data('companyid');
    }).get();
    alert(companyList);
}

The .get() call is necessary to turn the result of .map() into a plain array.

See http://jsfiddle.net/alnitak/zfUXj/

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • I have never used the map method. That looks really easy though. – Evik James Aug 24 '12 at 18:59
  • 1
    @EvikJames FYI - `map` comes from functional programming languages such as LISP and Haskell. It transmogrifies one array into another array, by applying the supplied function to each element of the original array. – Alnitak Aug 24 '12 at 19:18
2

Why not something like this, and put them in an array?

var checkedCompanys = new Array();
 $('input.company:checked').each(function() {
     checkedCompanys.push($(this).data("companyid"));    
  });

Good luck

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
maxijb
  • 541
  • 4
  • 13