【问题标题】:Unable to get values of checkboxes with jQuery无法使用 jQuery 获取复选框的值
【发布时间】:2013-09-06 13:27:51
【问题描述】:

我正在尝试使用 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>";

【问题讨论】:

  • 你设置了id mate,而不是class,所以它应该是#selectFemaleService:checkedid 似乎也是复数形式。
  • 你的代码输出了多少个复选框?如果不止一个,那么您就是在复制 ID,这是不行的。
  • 选择器使用#作为id有错误
  • 我也试过用#,但没有得到输出。

标签: php javascript jquery checkbox


【解决方案1】:

您的 jQuery 是由 class 选择的,但您的复选框有一个 id。如果有多个复选框,您应该将id 更改为class,这样您就不会出现重复。

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

【讨论】:

  • 如果你在 PHP 中运行它,你会得到 0 作为结果
  • @d4rkpr1nc3 谢谢,忘记了 PHP 中的连接字符是什么。
  • 酷! +1 解释:)
【解决方案2】:

你应该使用 input name 而不是 class 来使用 jQuery 选择它

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

【讨论】:

  • 一个小的修正伙伴,nameselectFemaleServices。注意复数:)
  • 另外你需要混合你的引号,你现在拥有的会给你一个语法错误。
  • 正如哈利所说,我的名字和选择器不匹配!这就是问题所在!
  • 谢谢@Harry & RoryMcCrossan,我的错!
【解决方案3】:

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

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/

【讨论】:

    【解决方案4】:

    试试这个:

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

    http://jsfiddle.net/JPvwJ/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 2012-07-02
      • 2012-12-20
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      相关资源
      最近更新 更多