在点击事件上克隆整个div标签

时间:2015-05-23 10:17:17

标签: javascript jquery html

我想在每次单击“添加更多”按钮时克隆整个div标签..我试过但它不起作用。

HTML

 <div id="student" class="row"><br/><br/>
          <div class="col-sm-6">
              <div class="form-group">
                  <label class="control-label">Firstname</label>
                  <label style="color:red;" id="std_first_name_error"></label>
                  <div class="append-icon">
                      <input type="text" id="std_first_name" name="std_first_name1" id="password" class="form-control" placeholder="Enter first name" minlength="4" maxlength="16" required>
                      <i class="icon-lock"></i>
                  </div>
              </div>
          </div>
          <div class="col-sm-6">
              <div class="form-group">
                  <label class="control-label">Select School</label>
                  <label style="color:red;" id="std_scl_error"></label>
                  <div class="option-group">
                    <select id="std_scl_name" name="std_scl_name" class="language" required>
                      <option value="">Select school..</option>

                    </select>
                  </div>
                </div>
          </div>
      </div>
      <button id="add_student" class="btn btn-embossed btn-primary">Add More</button>

Jquery的

<script type="text/javascript">

        $(document).ready(function(){       
            var count = 2;
            $('#add_student').click (function(e){
                e.preventDefault()
                var clonedEl = $('#student').first().clone()
                clonedEl.find(':text').attr('name','std_first_name'+count)
            });
            });
    </script>

应用

enter image description here

1 个答案:

答案 0 :(得分:2)

您必须创建一个包含所有学生的div

<div id="all">
    <div id="student" class='row'>--Your old stuff here</div>
</div>

改变js中的内容

$(document).ready(function(){       
        var count = 2;
        $('#add_student').click (function(e){
            e.preventDefault();
            var clonedEl = $('#student').first().clone();
            clonedEl.find(':text').attr('name','std_first_name'+count);
            //Add the newly div the the entire div
            $('#all').append(clonedEl);
    });
});