Saturday 17 March 2012

DYNAMICALLY CLONING HTML CONTROLS USING JQUERY



Here is a complete example and walkthrough for dynamically cloning a container that has a set of HTML controls.
I used jquery for scripting, so included the library reference in the head section.
<head> 
   <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>

</head>
As for the body, let's add a button to open up our modal dialog.
<body>
...  
<div id="calc-se-buttons">
    <input type="button" value="Print" id="print" name="print" class="button" />
</div>
Let's now create a container that has the contents that we intend to clone. In this example, we will clone the container with the id print-input, . Assigning a style (print-input-style) to the container which we want to clone is important here, because later we will depend on style name while calculating the number of cloned elements that we currently have.
<div id="print">
    <br/>
    <div id="print-input-1" class="print-input-style" >
        <label for="modal-print-title-1">Title</label>&nbsp;
        <select name="modal-print-title-1" id="modal-print-title-1">
                <option value='Mr'>Mr</option>
                <option value='Miss'>Miss</option>
                <option value='Ms'>Ms</option>
                <option value='Mrs'>Mrs</option>
                <option value='Dr'>Dr</option>
                <option value='Fr'>Fr</option>
            </select>&nbsp;&nbsp;
        <label for="modal-print-name-1">First Name</label>&nbsp;
        <input name="modal-print-name-1" id="modal-print-name-1" type="text" size="6" />&nbsp;&nbsp;
        <label for="modal-print-surname-1">Last Name</label>&nbsp;
        <input name="modal-print-surname-1" id="modal-print-surname-1" type="text" size="6" />
        <br/>
    </div>
    <br/><br/>
    <div id="div-add-customer">
        <img id="add-customer" src="../images/add-more.gif" alt="Add New Customer" width="20" height="20" />
    </div>
</div>

Next, let's implement the jquery function that clones the print-input container and bind it to the add-customer button.
This function simply counts the current number of clonable elements, clones one of them and assigns an incremented number for each of the element ids. So, as new elements are added, main container ids go one after the other like print-input-1, print-input-2,.... The ids of the contained controls are also incremented accordingly.
There is a business rule to limit the number of added elements to 4. This is quite useful if you want to keep the size of your container consistent or limit the number of elements for some reason.



$(document).ready(function () {
  $('#add-customer').click(function () {
    // how many "duplicatable" input fields we currently have
    var num = $('.print-input-style').length;
    // the numeric ID of the new input field being added 
    var newNum = new Number(num + 1);      
        
    var currentContainerId = '#print-input-' + num;
 
    // create the new element via clone(), and manipulate it's ID using newNum
    var newElem = $(currentContainerId).clone().attr('id''print-input-' + newNum);
 
    // manipulate the name/id values of the input inside the new element
    $(currentContainerId).children('label').each(function (i) {
      var attrFor = $(this).attr('for');
      $(this).attr('for', attrFor.substring(0, attrFor.lastIndexOf("-") + 1) + newNum);
    });
    $(currentContainerId).children('select').each(function (i) {
      var attrId = $(this).attr('id');
      var attrName = $(this).attr('name');
      $(this).attr('id', attrId.substring(0, attrId.lastIndexOf("-") + 1) + newNum)
        .attr('name', attrName.substring(0, attrName.lastIndexOf("-") + 1) + newNum);
    });
    $(currentContainerId).children('input').each(function (i) {
      var attrId = $(this).attr('id');
      var attrName = $(this).attr('name');
      $(this).attr('id', attrId.substring(0, attrId.lastIndexOf("-") + 1) + newNum)
        .attr('name', attrName.substring(0, attrName.lastIndexOf("-") + 1) + newNum);
    });
 
    // insert the new element after the last "duplicatable" input field
    $(currentContainerId).after(newElem);
 
    // business rule: you can only add 4 names
    if (newNum == 4)
      $('#add-customer').attr('disabled''disabled');
    });
});

There, each time you hit the plus button (add-customer), the entire row is duplicated.
 

No comments:

Post a Comment