Currently, I am working on a jQuery clone project where I need to dynamically add and delete rows. Despite searching extensively on Stack Overflow and Google, I only have a basic understanding of how jQuery clone works.
Any suggestions would be greatly appreciated.
Below is the jQuery code I am using:
var count=0;
$(document).on("click", ".phn_btn_more", function () {
var $clone = $('.cloned-row:eq(0)').clone();
$clone.find('[id]').each(function(){this.id+='someotherpart'});
$clone.attr('id', "added"+(++count));
$('.cloned-row:eq(0)').after($clone);
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row').length;
if(len > 1){
$(this).closest(".btn_less1").parent().parent().parent().remove();
}
});
Although I can now increment IDs dynamically with this updated code, it seems to be cloning two times instead of once.
When clicking the "add more" button, the div is being cloned but instead of one, I am getting two duplicated divs. Additionally, I am trying to increment ID and name dynamically.
I understand that this may be considered a possible duplicate issue, but I am still unsure why I am unable to increment the ID and name. Also, for the first div, the 'btn_less' class won't be available and should only appear after the user clicks 'add more' from the second instance onwards.
Below is the HTML code snippet:
<div class="em_pho cloned-row" id="phone_content">
<select id="sel_phntype" name="sel_phntype" class="sslt_Field">
<option selected='selected' value="">Phone Type</option>
<option value="BUSN">Business</option>
<option value="CAMP">Campus</option>
<option value="CELL">Cellphone</option>
<option value="CEL2">Cellphone2</option>
<option value="FAX">FAX</option>
<option value="HOME">Home</option>
<option value="OTR">Other</option>
</select>
<span class="ph-inline">
<input type="text" class="cc_field" placeholder="Country Code" id="txt_CC" maxlength="3" name="txt_CC" />
<input type="text" class="pn_field" placeholder="Phone Number" id="txt_Pno" name="txt_Pno" />
<input type="radio" name="preferred" id="rad_Prf" value="preferred">
<label class="radio-label">Preferred</label>
<input type="button" class="phn_btn_more" id="buttonvalue"/>
</span>
</div>
Your assistance on this matter will be much appreciated.
Thanks & regards, Mahadevan