简体   繁体   中英

JavaScript stops working after post

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 %}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM