Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Django Dynamic Formset and Select2 together in the same page?

I have successfully used Django Dynamic Formset and Select2 separately. However, when I am using select2 and adding more forms in my formset dynamically, the added forms wouldn't work for the dropdowns. I click on them but the dropdowns wouldn't open.

<script type="text/javascript">
    $(function() {
        $('.trt').formset();
    });

    $('select').select2();
</script>

How can I edit the above code so that select2 works for my added forms?

like image 882
MiniGunnR Avatar asked Oct 24 '25 21:10

MiniGunnR


2 Answers

what worked for me is adding an on.click statement to call the select2 for the class .add-row after the formset script at the end of the document. Like this:

<script>
$( ".add-row" ).click(function() {
  $('.forselect2').select2();
});
</script>

Not sure if its still relevant for you just added in case someone also finds this. For your case, just replace '.forselect2' with 'select2' and see if it works.

like image 84
Greg Avatar answered Oct 27 '25 12:10

Greg


I can tell you from my personal experience that Django-Dynamic-Formset doesn't behave well with other apps/tools on the same field. In some cases lots of alteration is needed to get it to work when other JS is present.

Take a look at this: (this one is using django_select2 and not select2) https://github.com/anneFly/django-dynamic-formset-select2-poc

It hasn't been updated for a while but you can see at the end it addresses some of the conflicts.

like image 37
morinx Avatar answered Oct 27 '25 12:10

morinx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!