Search code examples
javascriptjqueryclone

Change label to match numeric part from ID


I have this HTML code:

<div id="wrapper">
  <div class="row">
    <label for="additional_1">Additional #1 :</label>
    <input type="text" id="additional_1" name="pnr_remarks_modify[additional][]">
    <a href="#" class="addInput">New</a> - <a href="#" class="removeInput">Remove</a>
  </div>
</div>

And I am adding (cloning) / removing the complete '.row' element with this code:

var cloneCntr = 2;
$('#wrapper').on('click', '.addInput', function() {
  // clone the div
  var row = $(".row").last();
  var clone = row.clone();

  // change all id and name values to a new unique value
  $("*", clone).add(clone).each(function() {
    if (this.id) {
      this.id = (this.id).slice(0, -1) + cloneCntr;
    }
    if (this.name) {
      this.name = this.name;
    }
  });
  ++cloneCntr;
  $('#wrapper').append(clone);
});

$('#wrapper').on('click', '.removeInput', function(e) {
  e.preventDefault();
  var target = $(e.currentTarget);
  target.parent().remove();
})

Every time I click on New I got a clone from the previous object but changing its ID. For example:

First Click on New

Additional #1 : New - Remove

Second Click on New

Additional #1 : New - Remove

But as you can see the for attr and the label text remain the same. I need to change them to (on each new clone):

  • for needs to be the same as the new ID
  • label text needs to be Additional # + cloneCntr

But I don't know how to achieve this part, can I get some help?

Here is the jsFiddle where I am playing around this


Solution

  • You can loop through all the rows each time one is added or removed and update based on row index. Use one function that gets called within both event handlers

    $('#wrapper').on('click', '.addInput', function() {
      var clone = $(".row").last().clone();
      clone.find('input').val(''); // clear value on clone input
      $('#wrapper').append(clone);
      updateCounts();
    });
    
    $('#wrapper').on('click', '.removeInput', function(e) {
      e.preventDefault();
      var target = $(e.currentTarget);
      target.parent().remove();
      updateCounts();
    });
    
    
    function updateCounts() {
      $('#wrapper .row').each(function(i) {
        var num = i + 1,
          $row = $(this),
          inputId = 'additional_' + num;
    
        $row.find('label').text('Additional #' + num + ' :').attr('for', inputId);
        $row.find('input').attr('id', inputId)
      });
    
    }
    

    DEMO