Mr.M
Mr.M

Reputation: 1490

JQuery clone incrementing id was not coming sequence and for deleting the row also

currently working jQuery clone where I am increment id for the entire div with my current code Increment was working but not in sequence expy -1 and if user click add more button it generating random id number expy-3. So once when I add the row I want to delete the row with my code i can able to delete the row but the id was not decrementing for example if i have expy-1, expy-2 expy-3 if i delete expy-2 the expy-3 id has to change expy-2 because already i had expy1

Here is the jquery code

$(document).on("click", ".exp_add_button", function() {
var $clone = $('.cloned-row3:eq(0)').clone(true, true);
var num = $('.cloned-row3').length;
$clone.find(".chk_Field_exp").val('');
  $clone.find('[id]').each(function() {
    this.id += '_' + num;
    $(this).removeClass("errRed");
    if ($(this).hasClass("required_Field")) {
      $(this).prevAll('label').find('span.required-star').removeClass('text-error-red');
      $(this).addClass("cloned_field");
    } else {
      $(this).removeClass("errRed");
      $(this).removeClass("text-error-red");
    }
  });
$clone.find('.btn_more').after("<input type='button' class='btn_less1 edu_btnle' id='buttonless" + (++rowCount) + "'/>")
$clone.attr('id', "expy-" + (++rowCount)).addClass('exp_add');
$clone.find(".startDate").val('');  
$clone.find(".endDate").val('');
/*$clone.find(".degree_Description").attr('disabled', true).val('');*/
$clone.find(".startDate,.endDate")
  .removeClass('hasDatepicker')
  .removeData('datepicker')
  .datepicker({
    dateFormat: "mm/dd/yy",
    changeMonth: true,
    yearRange: "-100:+0",
    changeYear: true,
    maxDate: new Date(),
    showButtonPanel: false,

    beforeShow: function() {
      setTimeout(function() {
        $('.ui-datepicker').css('z-index', 99999999999999);

      }, 0);
    }
  });

$(this).parents('.wrk_exp').after($clone);
});

Here is the code for delete

  $(document).on('click', ".btn_less1", function() {
var len = $('.cloned-row3').length;
if (len > 1) {
  $(this).closest(".btn_less1").parent().parent().parent().remove();
}

});

Here is the fiddle link

Thanks in advance

Upvotes: 0

Views: 149

Answers (1)

void
void

Reputation: 36703

This is because you are increasing the value of rowCount twice, in these two line:

$clone.find('.btn_more').after("<input type='button' class='btn_less1 edu_btnle' id='buttonless" + (++rowCount) + "'/>")
$clone.attr('id', "expy-" + (++rowCount)).addClass('exp_add');

Remove one ++ from the bottom rowCount, code will be:

$clone.find('.btn_more').after("<input type='button' class='btn_less1 edu_btnle' id='buttonless" + (++rowCount) + "'/>")
$clone.attr('id', "expy-" + (rowCount)).addClass('exp_add');

Fiddle

++rowCount changes the value of rowCount and is equal to

rowCount = rowCount+1

Upvotes: 1

Related Questions