javascript - 通过不同的 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>
解决方案
每次在编辑按钮上单击添加选中属性但您忘记删除先前选中复选框的选中属性。所以你需要取消选中编辑按钮上的所有复选框,如下所示。
$("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>
推荐阅读
- flask - 一种检测烧瓶中会话过期的方法?
- r - R Markdown code chunk does not show math equations
- vba - Word 中的 VBA 宏用于选择和分组图像,并在其顶部带有突出显示框(形状)
- javascript - 创建一个 NEXT 和 PREVIOUS 来显示 JSON 数据的记录
- javascript - 从 JS 获取图像数组到 Django 模板
- algorithm - 给定一个比较列表,用尽可能少的额外比较对项目进行排序
- javascript - 使用颤振客户端向 node.js express api 发出 post 请求
- c - 在 C 中为未知长度的字符串实现 BST 的最佳实践是什么?
- task - 任务计划程序无法运行应用程序
- javascript - Google Apps 脚本 - 自动链接工作表