Dynamically adding a form to a Django formset with Ajax

后端 未结 15 2107
不思量自难忘°
不思量自难忘° 2020-11-22 03:09

I want to automatically add new forms to a Django formset using Ajax, so that when the user clicks an \"add\" button it runs JavaScript that adds a new form (which is part o

15条回答
  •  春和景丽
    2020-11-22 03:33

    Another cloneMore version, which allows for selective sanitization of fields. Use it when you need to prevent several fields from being erased.

    $('table tr.add-row a').click(function() {
        toSanitize = new Array('id', 'product', 'price', 'type', 'valid_from', 'valid_until');
        cloneMore('div.formtable table tr.form-row:last', 'form', toSanitize);
    });
    
    function cloneMore(selector, type, sanitize) {
        var newElement = $(selector).clone(true);
        var total = $('#id_' + type + '-TOTAL_FORMS').val();
        newElement.find(':input').each(function() {
            var namePure = $(this).attr('name').replace(type + '-' + (total-1) + '-', '');
            var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
            var id = 'id_' + name;
            $(this).attr({'name': name, 'id': id}).removeAttr('checked');
    
            if ($.inArray(namePure, sanitize) != -1) {
                $(this).val('');
            }
    
        });
        newElement.find('label').each(function() {
            var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
            $(this).attr('for', newFor);
        });
        total++;
        $('#id_' + type + '-TOTAL_FORMS').val(total);
        $(selector).after(newElement);
    }
    

提交回复
热议问题