Pete
Pete

Reputation: 88

Javascript array not working as expected

I'm pretty new to js/jquery. For each checkbox with the ID of check$ (where $ is a sequential number), I want to toggle the class "agree" of the surrounding span that uses the same check$ (but as a class). I don't want to have to hard-code the list of matching checkboxes, as this may vary.

Here's my code. This function works as expected:

agree = function (checkbox, span) {
    $(checkbox).change(function(){
       $(span).toggleClass('agree');
   });      
};

This is what I'm trying to pass to the above function, which does not work:

$(function() {
    var elemid = 'check',
    checks     = Array($('[id^='+elemid+']').length);
    console.log(checks);
  for (i=0; i < checks; i++) {
    agree('#'+elemid+checks[i], "."+elemid+checks[i]);
    }
});

console.log(checks) returns [undefined × 4]. The number of elements is correct, but I don't know why it's undefined, or whether that is even significant.

The following code works as expected, but as I say, I'd rather not have to specify every matched element:

$(function() {
    var checks = ["check1", "check2", "check3", "check4"];
    for (i=0; i < checks.length; i++) {
        agree('#'+checks[i], "."+checks[i]);
        }
});

Thanks.

Edit: Thanks to Jack, I was overlooking the most simple method. I added the same class to all checkboxes and spans, and solved the problem with this:

$('input.check').change(function(){
    $(this).closest('span.check').toggleClass('agree');
});

Upvotes: 2

Views: 192

Answers (2)

Guffa
Guffa

Reputation: 700910

The reason that the array is full of undefined values, is that you are just getting the number of items in the jQuery object, and create an array with that size. The jQuery object is discarded.

Put the jQuery object in the variable instead:

var elemid = 'check', checks = $('[id^='+elemid+']');

checks.each(function(){
  agree(this, "."+elemid+checks[i]);
});

Upvotes: 0

Jack
Jack

Reputation: 8941

I might be totally missing something, but I'm pretty sure you are just trying to attach a change handler to each checkbox. In this case you can give them all the same class. I'm also guessing at your html structure for the span.

For reference:

http://api.jquery.com/closest/

http://docs.jquery.com/Tutorials:How_jQuery_Works

$('.yourcheckboxclass').change(function(){ //grab all elements with this class and attach this change handler
   $(this).closest('span').toggleClass('agree'); 
});

Upvotes: 1

Related Questions