0

我正在为包含checkboxes. 即我从这个表格提交数据,然后在提交时有一个条款来编辑以前提交的数据。

我有一个包含提交的复选框值的数组。所以我想要每个复选框的值包含在 中php array,我想让它们使用jQuery.

我在下面尝试过:

HTML:

<?php
foreach ($selections as $selection) {
echo "<tr><td>" . $selection -> Name . "</td><td><input type=checkbox id=" . $selection -> Name . " name=selections[] value=" . $selection -> id . " /></td></tr>";
}?>

脚本:

var checkboxarray = <?php echo json_encode($checkboxarray) ?>;

        $.each(checkboxarray, function (i, elem){

        if(elem.name == $('input[name ="selections[]"]').attr('id')){

            $('input[name ="selections[]"]').attr('checked','checked');

            }

        })

但是,它似乎无法正常运行。

帮助表示赞赏,谢谢。

4

3 回答 3

1

你可以这样做:

$.each(checkboxarray, function (i, elem){
    if($('#'+elem.name) != 'undefined'){
        $('#'+elem.name).attr('checked', true);
    }
});
于 2012-10-04T07:27:48.353 回答
1

您可以id直接在选择器中查找属性:

$.each(checkboxarray, function (){
        if($('#' + this.name).length){
            $('#' + this.name).attr('checked','checked');
        }
    });
});
于 2012-10-04T07:29:29.510 回答
1

你也可以

尝试

foreach ($selections as $selection) {
    $checked    =   in_array($selection -> Name, $checkboxarray ) ? 'checked="checked"' : '';
echo "<tr><td>" . $selection -> Name . "</td><td><input type=checkbox id=" . $selection -> Name . " name=selections[] value=" . $selection -> id . " ".$checked."/></td></tr>";
}

$checkboxarray是您检查的数组列表

于 2012-10-04T07:29:40.607 回答