nimrod
nimrod

Reputation: 5732

Unable to get values of checkboxes with jQuery

I am trying to get all selected checkbox values with JavaScript, but I have not been able to accomplish it until now. This is what I have tried. What am I doing wrong?

JS:

var femaleMatches = [];
$(".selectFemaleService:checked").each(function() {
    console.log('found a female');
    femaleMatches.push(this.value);
});

PHP:

echo "<div class='checkbox'><label><input id='selectFemaleServices' name='selectFemaleServices' type='checkbox' value='$id'>$description</label></div>";

Upvotes: 0

Views: 313

Answers (4)

BrownEyes
BrownEyes

Reputation: 2287

You should use the input name instead of the class to select it using jQuery

$("input[name='selectFemaleServices']:checked").each(function() {

Upvotes: 2

Adam Moszczyński
Adam Moszczyński

Reputation: 3556

try this:

    var femaleMatches = [];
    $(".selectFemaleService").each(function() {
        if(this.checked){
        console.log('found a female');
        femaleMatches.push(this.value);
        }
    });

http://jsfiddle.net/JPvwJ/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your jQuery is selecting by class, yet your checkboxes have an id. If there are multiple checkboxes you should change the id to class so you don't end up with duplicates.

echo "<div class='checkbox'>" 
        . "<label>"
            . "<input class='selectFemaleServices' name='selectFemaleServices' type='checkbox' value='$id'>$description"
        . "</label>"
    . "</div>";

Upvotes: 4

Robert
Robert

Reputation: 386

I think this will help, the included fiddle shows how it does populate the array. You might need to change the way in which it is adding / or add remove functionality, but this will get you the value in the array

var femaleMatches = [];
$(".selectFemaleService").click(function() {
    if($(this).is(':checked')){
        console.log('found a female');
        femaleMatches.push($(this).val()); 
        console.log(femaleMatches);
    }
});

http://jsfiddle.net/8uZ3e/

Upvotes: 0

Related Questions