I am creating a dynamic form using formsets. So basically when user click on "Add Field" button a new form will be created and when user click on trash icon the form should be removed !
Now the problem is that, delete icon is displaying on first default form also so if the click on the icon the default form also gets removed ! How to add delete icon on the cloned forms ?
<script>
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
var row = $('.dynamic-form:first').clone(true).get(0);
$(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden');
$(row).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, formCount);
$(this).val('');
});
$(row).find('.delete-row').click(function() {
deleteForm(this, prefix);
});
$('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1);
return false;
}
function deleteForm(btn, prefix) {
$(btn).parents('.dynamic-form').remove();
var forms = $('.dynamic-form');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, i);
});
}
return false;
}
</script>
<script>
$(function () {
$('.add-row').click(function() {
return addForm(this, 'form');
});
$('.delete-row').click(function() {
return deleteForm(this, 'form');
})
})
</script>
This is the snippets am using, i need to add
<a id="remove-{{ form.prefix }}-row" href="javascript:void(0)" class="delete-row">Delete <em class="icon ni ni-trash-fill text-danger fs-15px"></em></a>
on the cloned form alone, default form should not contain this ! Please help
Delegate
Change 'tr' to 'form' if it is a form or '.row' for whatever a '.row' is
$("#tb").on('click', '.delete-row', function() {
$(this).closest('tr').remove()
});
tbody tr:first-child button.delete-row {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
<tbody id="tb">
<tr>
<td>Row 0</td>
<td><button class="delete-row">Click 0</button></td>
</tr>
<tr>
<td>Row 1</td>
<td><button class="delete-row">Click 1</button></td>
</tr>
<tr>
<td>Row 2</td>
<td><button class="delete-row">Click 2</button></td>
</tr>
</tbody>
</table>