【问题标题】:Clone checkbox when checked选中时克隆复选框
【发布时间】:2018-12-29 14:49:04
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery checkbox onchange


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

    注意:通过在$('.sth').html(clone); 中使用html(),它会一次又一次地改变整个html,所以你不会注意到代码的效果.. 所以我把html( 改为append( 让你看到代码是有效的

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2014-07-27
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2019-05-14
      • 2015-01-24
      • 1970-01-01
      • 2010-10-19
      相关资源
      最近更新 更多