Search code examples
clonejqueryjquery-click-event

How to add an increment value for each id attribute within the div contents with cloned jQuery object


Having a hard time figuring out how to add an increment value for each id attribute within the div contents with cloned jQuery object.

http://jsfiddle.net/hvK8d/

===================== HTML=====================

    <div class="upload-file-container">
  <div class="uploadFile left clearfix">
    <input type="file" id="FileUpload1">
    <table id="RadioButtonList1">
      <tbody>
        <tr>
          <td><input type="radio" value="Resume"  id="RadioButtonList1_1">
            <label for="RadioButtonList1_1">Resume</label></td>
          <td><input type="radio" value="Letter of Recommendation"  id="RadioButtonList1_2">
            <label for="RadioButtonList1_2">Letter of Recommendation</label></td>
          <td><input type="radio" value="Other"  id="RadioButtonList1_3">
            <label for="RadioButtonList1_3">Other</label></td>
        </tr>
      </tbody>
    </table>
  </div>
  <a href="javascript:;" class="remove left">Remove</a> </div>
<div class=""><a class="plus" href="javascript:;">plus one</a></div>

===================== JQUERY =====================

    //Cloning upload file control
$('.remove').live('click', function () {
    if (confirm("Are you sure you wish to remove this item?")) {
        $(this).parent().slideUp('fast', function () {
            $(this).remove();
        });
    }
    return false;
});

$('.plus').click(function () {
    console.log('cloning');
    var divCloned = $('.upload-file-container:first').clone();
    divCloned.hide().insertAfter('.upload-file-container:last').slideDown('fast');
    return false;
});

Solution

  • For the sake of completeness I will put here a small solution making use of a "template."

    A class for hiding the template:

    .upload-file-container.template {
      display: none;
    }  ​
    

    A small function to do replacements:

    $.fn.template = function(variables) {
      return this.each(function() {
        this.innerHTML = this.innerHTML.replace(/{{(.+)}}/g, function(match, variable) {
          return variables[variable];
        });
        return this;
      });
    };
    

    A template:

    <div class="upload-file-container template">
      <div class="uploadFile left clearfix">
        <input type="file" id="FileUpload{{id}}">
        <table id="RadioButtonList{{id}}"><tbody>
          <tr>
            <td>
              <input type="radio" value="Resume"  id="RadioButtonList{{id}}_1">
              <label for="RadioButtonList{{id}}_1">Resume</label>
            </td>
          </tr>
        </tbody></table>
      </div>
    </div>
    

    Usage:

    var count = 0;
    
    var divCloned = $(".upload-file-container.template")
      .clone()
      .removeClass("template")
      .template({
        id: count++
      });