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/

2
  • 1
    $Company[i] gets the HTMLElement, you should be using $Company.eq(i). And the code in your jsFiddle is quite different from what you posted here... Commented Aug 24, 2012 at 19:05
  • I have been updating the fiddle. Oops! Commented Aug 24, 2012 at 19:14

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I have never used the map method. That looks really easy though.
@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.
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

4 Comments

this is exactly what .map() is designed for - no need for push
@Roko you've unnecessarily re-evaluated the selector instead of re-using $Company
Good explanation on why to use []... I'll try map and get too. Thanks
+1 @Alnitak :) my bad! jsfiddle.net/aGZCG/1 I used initially [] (Cause I always do, but re-copying the code I forgot to change to it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.