无法使用 jQuery 获取复选框的值


Unable to get values of checkboxes with jQuery

我正在尝试使用 JavaScript 获取所有选定的复选框值,但直到现在我都无法完成。这就是我尝试过的。我做错了什么?

.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>";

您的 jQuery 正在按 class 进行选择,但您的复选框有一个id。如果有多个复选框,则应将id更改为class,以免最终出现重复项。

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

你应该使用输入名称而不是来使用 jQuery 选择它

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

我认为这会有所帮助,包含的小提琴显示了它如何填充数组。您可能需要更改添加/或添加删除功能的方式,但这将为您提供数组中的值

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/

试试这个:

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

http://jsfiddle.net/JPvwJ/