我的问题:第一次我单击编辑按钮,然后根据数据库表值选中了复选框,然后第二次我单击其他编辑按钮,然后未取消选中第一次复选框值,我不知道我的代码有什么错误。 请检查我的代码。
示例:在Form屏幕截图中,当我单击第一个编辑按钮时,然后选中了复选框值(如cricket,hokky,chess);在第二个编辑按钮后,我单击了复选框值(cricket),但问题是第一次复选框的值(例如板球,嬉皮,象棋)未被选中,请帮助我,
请检查以下屏幕截图:
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>
答案 0 :(得分:0)
每次在编辑按钮上单击添加的已选中属性,但您忘记删除先前已选中复选框的已选中属性。因此您需要取消选中“编辑”按钮上的所有复选框,如下所示。
$("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>