选中时克隆复选框

时间:2018-12-29 14:49:05

标签: javascript jquery checkbox onchange

我希望能够单击它时克隆一个复选框,并且克隆的复选框将被取消选中。选中克隆复选框后,它将自动克隆并重复该过程。

                        <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/

1 个答案:

答案 0 :(得分:0)

  • 要取消选中新创建的复选框,可以使用.find('.others:checkbox').prop('checked' , false).end();
  • 如果您需要为动态生成的checkbox使用click事件,则需要使用$(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>

注意::在html()中使用$('.sth').html(clone);将会一次又一次地更改整个html,因此您不会注意到代码的效果..所以我更改了html(append(,让您看到代码有效