-4

I am trying to clone a div without its value. Everything I've tried so far copies the value as well.

Here is my jQuery function

$('#add_more').click(function(){
  $('#div_to_clone).clone().insertBefore('#add_more').find('input').val('');
});
Legionar
  • 7,472
  • 2
  • 41
  • 70
Ajit Das
  • 31
  • 4

2 Answers2

3

This seems to be working fine for me:

$('#add_more').click(function() {
    $('#div_to_clone').clone().insertBefore('#add_more').find('input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="div_to_clone">
  <input type="text" />
</div>
<a href="#" id="add_more">Add more</a>

Well, I recommend you changing your id to a class since the value of id attribute should be unique throughout the page. You might be getting the issue in some browser due to duplicate id.

$('#add_more').click(function() {
  $('.div_to_clone:first').clone().insertBefore('#add_more').find('input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="div_to_clone">
  <input type="text" />
</div>
<a href="#" id="add_more">Add more</a>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
-1

Assuming that your html code is similar to this.

<div class="ContainerDiv">
<div id=ClonethisDiv><input class="InputTxtBox" type="text" /></div>
</div>
<a href="#">clone</a>

Now, $("body").on("click", "a", function() { $("#ClonethisDiv").clone().appendTo(".ContainerDiv").find(".InputTxtBox").val(""); });

Hence on click, anchor tag u will able to get a copy of Div with Id='ClonethisDiv' and appended to the container Div. Here while cloning(copy) input element with a class '.InputTxtBox', will be emptied and get copied. No worry! TextBox Values which already appended to container Div doesnot change. Hope this will help you.

rajiv
  • 64
  • 1
  • 6