javascript - 选中时克隆复选框
问题描述
我希望能够在单击复选框时克隆它,并且克隆的复选框将被取消选中。检查克隆的复选框时,它将克隆本身并重复过程。
<section class="misc">
<div class="row">
<label class="label"><input type="checkbox" class="others"> Others:</label>
</div>
<div class="row">
<div class="col-md-6"><input type="text" class="form-control" placeholder="Others"/></div>
</div>
</section>
<div class="sth"></div>
<!-- Clone the "Others" checkbox with textbox when the original checkbox is checked. I want each subsequent clone to be unchecked, then clone itself.. -->
<script>
$(".others").change(function(){
if($(this).is(':checked'))
{
var clone=$(this).parents('section').clone();
$('.sth').html(clone);
}
});</script>
现在,我只能克隆原始的,并且克隆的复选框被选中而不是未选中。
jsfiddle:http: //jsfiddle.net/cLkvxydh/
解决方案
- To unchecked the new created checkbox you can use
.find('.others:checkbox').prop('checked' , false).end();
- if you need to use the click event for the dynamically generated
checkbox
you'll need to use$(document).on('change',".others" ,function(){
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="misc">
<div class="row">
<label class="label"><input type="checkbox" class="others"> Others:</label>
</div>
<div class="row">
<div class="col-md-6"><input type="text" class="form-control" placeholder="Others"/></div>
</div>
</section>
<div class="sth"></div>
<!-- Clone the "Others" checkbox with textbox when the original checkbox is checked. I want each subsequent clone to be unchecked, then clone itself.. -->
<script>
$(document).on('change',".others" ,function(){
if($(this).is(':checked'))
{
var clone=$(this).parents('section').clone().find('.others:checkbox').prop('checked' , false).end();
$('.sth').append(clone);
}
});</script>
Note: By using html()
in $('.sth').html(clone);
it will change the whole html again and again so you'll not notice the effect of the code .. So I changed html(
to append(
to let you see the code is work
推荐阅读
- c# - 读取列表成员值时动态获取类成员
- php - php curl -X GET 请求正文
- kubernetes - 无法获得作业 rke-network-plugin-deploy-job 的作业完成状态
- php - 如何使用 Guzzle 异步获取执行查询并按正确顺序处理它们?
- typescript - 防止接口具有名称为 X 的属性
- php - 在php laravel中合并多个数组
- javascript - 赛普拉斯 - 使用路由(选项)存根不起作用
- ios - Swift UI: relationship between the sheet and list views
- powershell - 使用循环创建对象的正确性
- r - 用于文本分类的 KNN,但 R 中 train 和 class 的长度不同