[通过ajax向php发送数据时如何检查复选框是否已选中

问题描述 投票:1回答:1

我有一个foreach循环,它在一个复选框和一些输入字段的内部创建tr's。每行都有一个ID为值的复选框。每行还有一个隐藏的输入字段,其id为值。

我想区分是通过每行自己的delete按钮发送请求,还是通过复选框发送对这些行进行检查的内容。 (当选中多个复选框时,我可以一次将其全部删除)

<tr>
    <input type="hidden" name="file_id" value="<?php echo $file_id; ?>" /> <!-- file id which belongs to each row -->
    <td><input type="checkbox" class="checkbox" value="<?php echo $file_id; ?>" /></td>
    ...
    <button class="btn btn-sm btn-danger submit" type="submit" name="delete_file">Delete</button>
</tr>

我通过jquery ajax将数据发送到php文件:

// checkboxes value 
    $(document).on('click' , '.submit' , function() { 
        var checkbox_value = [];
        var file_id = $(this).closest("tr").find("input[name='file_id']").val();


        $('.checkbox').each(function() {
            if ($(this).is(":checked")) {
                checkbox_value.push($(this).val());
            }
        });
        checkbox_value = checkbox_value.toString();
        $.ajax({
            url: "admin.php",
            method: "POST",
            data: {
                checkbox_value: checkbox_value,
                file_id : file_id

            },
            success: function(data) {
                $('.result').html(data);

            }
        });
    });

PHP:

if(isset($_POST["checkbox_value"])) {

        $checkboxfiles[] = $_POST["checkbox_value"];
        $category = $_POST["category"]; 

        // checkbox loop
        foreach ($checkboxfiles as $checkboxfile) {
            foreach(explode(',', $checkboxfile) as $id) {

                echo $id.'<br />';
                echo 'delete via checkbox is choosen';

            }
        }

        exit;
}

if(isset($_POST["file_id"])) {
        ...
        echo 'delete via single row is choosen';

}

问题:当我选择通过单行删除(未选中任何复选框)时,它仍会发送回显delete via checkbox is choosen

php jquery ajax checkbox checked
1个回答
0
投票

尝试此代码

if (this.checked) {
    checkbox_value.push($(this).val());
}
© www.soinside.com 2019 - 2024. All rights reserved.