0

I am using a script to control my Django formsets. The idea is to dynamically generate, remove and rename the forms. It works fine if the page was loaded for the first time, but if I try to submit the page and the forms get back from the POST, the old forms I can not delete. Although I can add and remove new ones.

function deleteForm(btn, prefix) {
    var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
    if (formCount > 1) {
        // Delete the item/form
        $(btn).parents('.item-wrapper').remove();
        var forms = $('.item-wrapper'); // Get all the forms
        // Update the total number of forms (1 less than before)
        $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
        var i = 0;
        // Go through the forms and set their indices, names and IDs
        for (formCount = forms.length; i < formCount; i++) {
            $(forms.get(i)).find('*').each(function () {
                updateElementIndex(this, prefix, i);
            });
        }
    } // End if
    else {
        alert("You must have at least one item in your invoice.");
    }
    return false;
}

Here is my HTML:

{{ formset.management_form }}

{% for form in formset %}
    <div class="item-wrapper">
        <div class="item-inner-wrapper">

            <div class="item-child-name">
                {{ form.name.label_tag }}
                <div class="ui-widget">{{ form.name }}</div>
            </div>
        </div>
    </div>

<!-- OTHER INPUTS --->

<div class="item-action-button">
    <a id="delete" href="#" class="button alt small special">Remove</a>
    <a id="hide-desc" class="button alt small">+ Description</a>
</div>
{% endfor %}
Ev.
  • 1,537
  • 1
  • 24
  • 49
  • Have you tried [debugging your javascript?](http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code) – Liam Sep 15 '15 at 09:18
  • Well, I am not a pro in JavaScript, I got that script from another tutorial. I tried to make some modifications and follow up debugging but I couldn't get much further debugging it. I will leave it open if someone can see something obvious I am not seeing. – Ev. Sep 15 '15 at 09:38

1 Answers1

0

I found out the button calling the function had the identifier as its ID inside the script. So when the script was called it got confused and didn't know which of the buttons was making the call. I simply changed the identifier for the class and now it is working good.

Ev.
  • 1,537
  • 1
  • 24
  • 49