栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Ajax将表单动态添加到Django表单集中

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Ajax将表单动态添加到Django表单集中

这就是我使用jQuery的方法:

我的模板:

<h3>My Services</h3>{{ serviceFormset.management_form }}{% for form in serviceFormset.forms %}    <div >    <table >        {{ form.as_table }}    </table>    </div>{% endfor %}<input type="button" value="Add More" id="add_more"><script>    $('#add_more').click(function() {        cloneMore('div.table:last', 'service');    });</script>

在一个javascript文件中:

function cloneMore(selector, type) {    var newElement = $(selector).clone(true);    var total = $('#id_' + type + '-TOTAL_FORMS').val();    newElement.find(':input').each(function() {        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');        var id = 'id_' + name;        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');    });    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);}

它能做什么:

cloneMore
接受
selector
作为第一个参数,
type
formset的形式作为第二个参数。什么是
selector
应该做的是把它传递它应该复制。在这种情况下,我将其传递给
div.table:last
jQuery,以查找带有类的最后一个表
table
。它的
:last
一部分很重要,因为
selector
还可用于确定将在其后插入新表格的内容。您很可能希望在其余表格的末尾使用它。该
type
论点是,这样我们就可以更新
management_form
领域,特别是
TOTAL_FORMS
,还有实际的表单字段。如果您有一个充满
Client
模型的表单集,则管理字段的ID为
id_clients-TOTAL_FORMS
id_clients-INITIAL_FORMS
,而表单字段的格式为
id_clients-N-fieldname
with
N
是表格编号,以开头
0
。因此,使用该
type
参数,该
cloneMore
函数将查看当前有多少个表单,并遍历新表单内的每个输入和标签,从而替换诸如
id_clients-(N)-name
to
id_clients-(N+1)-name
等的所有字段名称/ id 。完成后,它将更新
TOTAL_FORMS
字段以反映新表单并将其添加到集合的末尾。

此功能对我特别有用,因为它的设置方式使我可以在整个应用程序中使用它,以便在表单集中提供更多表单,而不必让我需要隐藏的“模板”表单来进行复制只要我通过它,表单集名称和表单的布局格式。希望能帮助到你。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387551.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号