Вопрос

I want to copy a div and all its content, to generate a cloned div (for example, adding lines to a invoice dinamically). I need to clone the content of the div, including html controls, dynamic ID and listeners for the elements in DIV!!

Is there an easy way to do this? Thanks!

enter image description here

The code works but it is not cloning the entire DIV it also Clone the Text box ID can some one help me.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>

<style>
body
{
    background: none !important;
}
</style>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <title>      Dynamically create input fields- jQuery </title>


    <link href="theme/css/ui/ui.base.css" rel="stylesheet" media="all" />

    <link href="theme/css/themes/black_rose/ui.css" rel="stylesheet" title="style" media="all" />



    <!--[if IE 6]>

    <link href="theme/css/ie6.css" rel="stylesheet" media="all" />



    <script src="theme/js/pngfix.js"></script>

    <script>

      /* Fix IE6 Transparent PNG */

      DD_belatedPNG.fix('.logo, ul#dashboard-buttons li a, .response-msg, #search-bar input');



    </script>

    <![endif]-->

 <script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
    </script>
    <script type="text/javascript">
      $(function() {
          var i = 1;
        $('#addNew').live('click', function() {
            var getParentId = $(this).closest('fieldset').attr('id');
            var getParentId1 = $('#'+getParentId);
            i = $('#'+getParentId+' p  input').size();
          if( i > 6 ) {
            alert("Limitation upto 5");
            return false;
          }
          $('<p><input type="text" id="p_new" name="p_new_' + i +'" value="" placeholder="I am New" /><a href="#" id="remNew">Remove</a> </p>').appendTo(getParentId1);
          i++;
          return false;
        });

        $('#remNew').live('click', function() {
          if( i > 2 ) {
            $(this).parents('p').remove();
            i--;
          }
          return false;
        });

        // Duplicate Query Block
        var addQueryBlock = $('#queryblock');
        var j = $('#queryblockfld').size() + 1;
        $('#addNewQueryBlock').live('click', function() {
          if( j > 6 ) {
            alert("Limitation upto 5");
            return false;
          }
          $('<fieldset id="queryblock' + j +'" name="queryblock' + j +'"><legend>Query Block' + j + '</legend><div style="float:right;" id="addqueryblock"><a style="text-decoration: none;" href="#" id="remNewFieldset"> &#8211; </a><a style="text-decoration: none;" href="#" id="addNewQueryBlock">+</a></div><div id="addinput"><p><input type="text" id="p_new1" name="p_new" value="" placeholder="Input Value" /><a href="#" id="addNew">Add</a><input type="text" id="input2" name="input2" value="" placeholder="input2" /></p></div></fieldset>').appendTo(addQueryBlock);
          j++;
          return false;
        });

         $('#remNewFieldset').live('click', function() {
          if( j > 2 ) {
            $(this).parents('fieldset').remove();
          j--;
          }
          return false;
        });
      });
    </script>

</head>


  <body>
    <h2>
      Dynamically Add Another Input Box
    </h2>

    <div id="queryblock">
      <fieldset id="queryblockfld" name="queryblockfld">
        <legend>
          Query Block
        </legend>
        <div style="float:right;" id="addqueryblock">
          <a style="text-decoration: none;" href="#" id="addNewQueryBlock">+</a></div>
          <div id="addinput">
            <p>
              <input type="text" id="p_new3" name="p_new3" value="" placeholder="Input Value" />
              <a href="#" id="addNew"> Add </a> Wlcome to my world
              <input type="text" id="input2"  name="input2" value="" placeholder="input2" />
            </p>
          </div>
        </fieldset>
    </div>
      </body>
    </html>
Это было полезно?

Решение 2

After a Long Search I found a working code which does what I wanted. Kindly refer the link

<div id="events_wrapper">
<div id="sub_events">
<p><label>Art Space </label>
<input type="text" id="as_name" name="as_name" class="txt-input small"/>
<input type="hidden" id="as_id" name="as_id" class="txt-input small"/>                                      
</p>

<p><label>Start Date </label>
<input type="text" id="start_date" name="start_date" class="datepicker txt-input small"/>

<label>End Date </label>
 <input type="text" id="end_date" name="end_date" class="datepicker txt-input small" />
</p>

<p><label>Opening Hours </label>
 From : <input style="width: 100px" type="text" id="time_from" name="time_from" class="timepicker txt-input small" />

To : <input style="width: 100px" type="text" id="time_to" name="time_to" class="timepicker txt-input small"/> </p>                                                    
</div>
     <br/>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />

JS Function:

$('#add_another_event').click(function() 
    {
        alert('test');var $address = $('#sub_events');
        var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
        var newNum = num + 1;
        var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');

        //set all div id's and the input id's
        newElem.children('div').each (function (i) {
            this.id = 'input' + (newNum*5 + i);
        });

        newElem.find('input').each (function () {
            this.id = this.id + newNum;
            this.name = this.name + newNum;
        });

        if (num > 0) {
            $('.clonedAddress:last').after(newElem);
        } else {
            $address.after(newElem);
        }

        $('.datepicker', newElem).removeClass('hasDatepicker').datepicker();
        $('#btnDel').removeAttr('enabled'); 
    });       

$('.datepicker').datepicker();                            

Also Refer Jquery date picker and time picker do not work when fields are dynamically created

Hope this will help some one.!

Working Example of the above code: http://jsfiddle.net/MkhZ2/24/

Другие советы

You can do it by using jQuery's .clone() method. Consider the following code :

//first clone your div
clonedDiv = $('#IdOfYourDIV').clone();

//use .attr() method to change the id
$(clonedDiv).attr('id','YourDynamicID');

Now your 'cloned' div is ready. But the handlers binded using the ID of the first div won't work on the clonedDIV.

I was dev something like this so my solution was very simple. Use clone to duplicate your div and appentTo set assuming the div are contained by body.

$("#btn_act").click(function(){
   var body = $("body"); //Where is contained the object
   var obj = $("#myDiv"); //Object who will be cloned
   var e = obj.clone(true).appendTo(body);
   $(e).find("input").each(function(){
       //ie: myInput0, myInput1 will be deleted
       if ($(this).attr("id") != 'myInput'){
          $(this).remove();
       }
   });
});

Think this would help you if you still need an small solution.

function duplicate() {
    var original = document.getElementById('duplicater' + i);
    var clone = original.cloneNode(true); // "deep" clone
    clone.id = "duplicetor" + ++i; // there can only be one element with an ID
    clone.onclick = duplicate; // event handlers are not cloned
    original.parentNode.appendChild(clone);
}

not duplicetor but duplicater :) then it will not show an error in console and add a cloned div

why wouldn't it clone input fields? it will clone it...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top