1

I have a selectable field that uses the django-select2 library. I am currently trying to copy the behaviour of the "add another" functionality present in the admin forms of Django.

I added a "+" icon to my regular form template and opened a popup so that the user can register a new item. This part works, now I wish to select the newly added item automatically once the popup is closed. I cannot seem to add a new option to the selectable, though.

I read the original dismissAddAnotherPopup() code and the select2 docs on that, but appending a new Option(...) to the element does not have the desired effect - in fact it adds as many options as I want, but they appear under the select box instead of in the dropdown menu, as if they were completely different things.

I looked at the html result and it seems the select2 field is not using <option ...> for the options rendered with Django, but rather some deeper nested elements for the options.

What is the correct syntax for adding new options in this situation?

Clara Daia
  • 149
  • 1
  • 1
  • 7

2 Answers2

0

What solved it for me was this answer:

let opt = "<option value=" + myValue + " selected='selected'>" + myValueText + "</option>";
$('#mySelect').html(opt);
$('#mySelect').val(myValue).trigger("change");

It looks a bit ugly to just replace the html, but as I mentioned in the question, appending a new Option(...) to the element did not work.

Clara Daia
  • 149
  • 1
  • 1
  • 7
0

Not fully client side, but might be helpful: you can use the django-addanother wrapper, like:

widgets = {
    'somefield': AddAnotherWidgetWrapper(Select2Widget, reverse_lazy('somefield_add')),
}

This will render a "+" next to the Select2 field; when pressing a popup will be opened which allows to add a new object. Once saved, the Select2Widget will be automatically populated with this newly created object.

SaeX
  • 17,240
  • 16
  • 77
  • 97