首页 > 解决方案 > 通过不同的 id 根据数据库值动态检查“爱好”复选框

问题描述

我的问题:我第一次单击编辑按钮然后根据数据库表值检查复选框,然后第二次单击其他编辑按钮然后第一次未选中复选框值,我不知道我的代码中有什么错误。请检查我的代码。

示例:在表单屏幕截图中,当我单击第一个编辑按钮时,我单击复选框值(如板球,hokky,国际象棋),然后在第二个编辑按钮后,我单击复选框值(板球)选中,但问题是第一次复选框值(如板球,hokky,chess) 未被选中,请帮助我,

请检查以下屏幕截图:

表格截图

HTML 代码:

    <form id="crudform" method="post">
        <label>Hobby:</label>
        <input type="checkbox" name="hobby[]" value="cricket">Cricket
        <input type="checkbox" name="hobby[]" value="hokky">Hobby
        <input type="checkbox" name="hobby[]" value="chess">Chess
        <input type="submit" name="submit" value="Add">
    </form>

<div class="table"></div>

数据库表截图

PHP代码:

<table>
        <thead>
            <tr>
                <th>Hobby</th>
                <th colspan="2">Action</th>
            </tr>
        </thead>
        <tbody>
            <?php if(mysqli_num_rows($result)>0){ ?>
                <?php while($data = mysqli_fetch_assoc($result)){ ?>
            <tr>
                <td><?php echo $data['hobby'];?></td>
                <td><button name="edit" data-id = <?php echo $data['id'];?> class="btn btn-info">Edit</button></td>
                <td><button class="btn btn-danger">Delete</button></td>
            </tr>
        <?php } ?>
        <?php } ?>
        </tbody>
    </table>

jQuery代码:

<script type="text/javascript">
$("button[name=edit]").click(function(){
    var id = $(this).attr("data-id");

    var hobbyss = [];
    $(":checkbox").each(function(index,element){
        hobbyss.push($(this).val());
    });


    $.ajax({
        url:"http://localhost/interview/crud_checkbox/edit.php",
        method:"post",
        data:{id:id},
        dataType:"json",
        success:function(response){
            var hobby = response.hobby.split(",");          // ["cricket", "hokky", "chess"]    

            $.each(hobby,function(index,element){
                if($.inArray(element,hobbyss) >= 0){
                    console.log($("input[value="+element+"]").prop("checked",true));
                }
            }); 
        }
    });
});
</script>

标签: javascriptphpjquerymysqlajax

解决方案


每次在编辑按钮上单击添加选中属性但您忘记删除先前选中复选框的选中属性。所以你需要取消选中编辑按钮上的所有复选框,如下所示。

$("button[name=edit]").click(function(){

	$('input[name=hobby\\[\\]]').prop('checked',false);
    
    //rest of your code here 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="crudform" method="post">
	<label>Hobby:</label>
	<input type="checkbox" name="hobby[]" value="cricket" checked >Cricket
	<input type="checkbox" name="hobby[]" value="hokky">Hobby
	<input type="checkbox" name="hobby[]" value="chess" checked >Chess
	<input type="submit" name="submit" value="Add">
</form>

<button name="edit" data-id ="1" class="btn btn-info">Edit</button>


推荐阅读