首页 > 解决方案 > 选中时克隆复选框

问题描述

我希望能够在单击复选框时克隆它,并且克隆的复选框将被取消选中。检查克隆的复选框时,它将克隆本身并重复过程。

                        <section class="misc"> 
                    <div class="row">
                     &nbsp;&nbsp;&nbsp;&nbsp;
                     <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/

标签: javascriptjquerycheckboxonchange

解决方案


  • 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">
     &nbsp;&nbsp;&nbsp;&nbsp;
     <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


推荐阅读