Yauheni Leaniuk
Yauheni Leaniuk

Reputation: 456

Select2 working incorrectly with Formsets

I have script like this and this working with only first form, others are frozen and did not work at all.

$(document).ready(function() {
    $('#id_membership-0-company').select2();
});

I'm not able to change # to . because of every new form have new id like id_membership-0-company, id_membership-1-company and so on, and all my forms have same class (this field don't have separate class)

I'm not able to just add all id's inside this function because of it works only when the page is loaded so only id 0 will work this way

I was try to do something like this: add onclick="addRow()" inside "Add form" button html tag and this code in script. Without Timeout function it doesn't work because script executes too fast. It works for two forms (if I press "Add form" button) but not working if I adding more id's (in this scenario after the second form many more incorrect forms created for this field)

function addRow() {
    function activateForms(){
        $('#id_membership-0-company').select2();
        $('#id_membership-1-company').select2();
        }
        setTimeout(activateForms, 1000);
    }

How to fix that? I need select2 widget for first field of every form?

Upvotes: 0

Views: 580

Answers (1)

Simone Rossaini
Simone Rossaini

Reputation: 8162

I create a small example for you, so you can adapt to your code.

$(document).ready(function() {
  $('select').select2();
});

$('.addSelect').on('click', function() {
  const arr = [{
      val: 1,
      text: 'One'
    },
    {
      val: 2,
      text: 'Two'
    },
    {
      val: 3,
      text: 'Three'
    }
  ];

  const sel = $('<select>').appendTo('.container');
  $(arr).each(function() {
    sel.append($("<option>").attr('value', this.val).text(this.text));
  });  
  $(sel).select2();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class='container'>
  <select>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
  </select>
</div>
<button class='addSelect'>Add Select2</button>

Upvotes: 1

Related Questions