通过不同的id根据数据库值动态选中“hobby”复选框

slwdgvem  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(213)

我的问题是:第一次单击编辑按钮,然后根据数据库表值选中复选框,第二次单击其他编辑按钮,然后第一次未选中复选框值,我不知道代码中有什么错误。请检查我的密码。
示例:在表单截图中,当第一个编辑按钮我单击然后复选框值(如cricket,hokky,chess)选中,第二个编辑按钮我单击之后复选框值(cricket)选中,但问题是第一次复选框值(如cricket,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>
cgfeq70w

cgfeq70w1#

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

$("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>

相关问题