【问题标题】:Help needed with using jquery to check checkboxes from php array使用 jquery 检查 php 数组中的复选框所需的帮助
【发布时间】:2011-05-22 13:31:35
【问题描述】:

我有一个 php 数组,我试图让 jQuery 来检查这些复选框,但我似乎无法让它工作。我的 php 数组名称是“toCheck”,即:

Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)

0,3,4 是我需要检查的复选框。这是我的复选框:

<input type="checkbox" name="correct[0]" id="correct" value="0" />
<input type="checkbox" name="correct[1]" id="correct" value="1" />
<input type="checkbox" name="correct[2]" id="correct" value="2" />
<input type="checkbox" name="correct[3]" id="correct" value="3" />
<input type="checkbox" name="correct[4]" id="correct" value="4" />
<input type="checkbox" name="correct[5]" id="correct" value="5" />

如果有人能指出使用什么 jQuery 来选择这些复选框,那就太好了!

<?php foreach($toCheck as $checkMe) { ?>
//i'm assuming my jquery goes here but I can't get it working
<?php }; ?>

提前谢谢你:)

【问题讨论】:

    标签: php jquery arrays checkbox


    【解决方案1】:

    您的 HTML 无效。 id 值在文档 (reference) 中必须唯一

    也就是说,忽略 id 值,您可以使用这个 (live example):

    $(':checkbox[name^=correct]').each(function() {
        switch (this.value) {
            case "0":
            case "3":
            case "4":
                this.checked = true;
                break;
         }
    });
    

    它使用name 属性上的CSS3 子字符串选择器(jQuery 支持几乎所有CSS3)来选择名称以correct 开头的任何复选框,然后使用jQuery 的each 循环它们。然后我们将checked 属性设置在具有所需value 的那些上。

    您也可以使用更长的选择器并且不使用循环 (live example):

    $(':checkbox[name^=correct][value=0], :checkbox[name^=correct][value=3], :checkbox[name^=correct][value=4]').attr('checked', true);
    

    更新:重新阅读您的问题,看来您可能需要更动态地执行此操作:

    <script type='text/javascript'>
    (function() {
        var boxes = $(); // Assumes jQuery 1.4 or higher
    <?php foreach($toCheck as $checkMe) { ?>
        echo "boxes.add(':checkbox[name=^=correct][value=" . $toCheck . "]');";
    <?php }; ?>
        boxes.attr('checked', true);
    })();
    </script>
    

    ...这将产生:

    <script type='text/javascript'>
    (function() {
        var boxes = $(); // Assumes jQuery 1.4 or higher
        boxes.add(':checkbox[name=^=correct][value=0]');
        boxes.add(':checkbox[name=^=correct][value=3]');
        boxes.add(':checkbox[name=^=correct][value=4]');
        boxes.attr('checked', true);
    })();
    </script>
    

    ...这将检查相关框。但这不会很有效(所有文档遍历),最好使用 PHP 将值组合到选择器或 switch 中,如上所示。

    【讨论】:

    • 非常感谢,我会修复我的 id 并使用上述内容:)
    【解决方案2】:

    请注意,浏览器不会提交未选中的复选框。

    请参阅Submit an HTML form with empty checkboxes 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多