[英]how to change id per form in select2 django formset
i need to increment id field forms per form我需要为每个表单增加 id 字段 forms
default id which django provides is id_formsetname_set-0-fieldName
and 0 increment one by one django 提供的默认 id 是
id_formsetname_set-0-fieldName
和 0 一一递增
in my case named id_items_set-0-model
and for second form will be id_items_set-1-model
it display in inspect element source code from browser, i used this for loo script在我的例子中名为
id_items_set-0-model
和第二种形式将是id_items_set-1-model
它显示在浏览器的检查元素源代码中,我将它用于 loo 脚本
for (var i = 0; i < 10; i++){
$("#id_items_set-"+i+"-model").select2();
}
but only worked for the first form, i dont want to use django-select2但只适用于第一种形式,我不想使用 django-select2
my template looks like this我的模板看起来像这样
this is my snippet这是我的片段
<tbody class="tbody tb1 " id="form_set"> {% for item in items.forms %} <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.model | add_class:'col-12 0model model' | attr:'id:id_items_set-0-model'}} </div> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', deleteText:'remove', addCssClass:'btn btn-success', }); }) </script> <script type="text/javascript"> $(document).ready(function(){ for (var i = 0; i < 10; i++){ $("#id_items_set-"+i+"-model").select2(); } }) </script>
only work for my first form then doesnt have any effect on other forms?仅适用于我的第一种形式,然后对其他 forms 没有任何影响? is there something i did wrongly in the script part please?
请问我在脚本部分做错了什么吗?
I have never worked on django.我从未在 django 上工作过。 Could you try this please.
你能试试这个吗? and if you could share with us a link for real example in case this doesn't work
如果您可以与我们分享一个真实示例的链接,以防万一这不起作用
$(()=>{
let ids = document.querySelectorAll("[id=*'id_items_set']");
ids.forEach((element)=>{
$(element).select2();
});
});
jquery.formset
has added
attribute we can call a function every time when a row created jquery.formset
added
属性,我们可以在每次创建行时调用 function
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
added:function($row){
$('.model').select2()
}
});
})
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.