I'm using Django-select2 to show select2 widgets on my forms. On one of these form select-fields I want to user to be able to set the value by clicking a link containing a suggestion.
My javascript looks like:
<script type="text/javascript">
$( document ).ready(function() {
// When the topicSuggestion is clicked, populate the select2 field with that value.
$('#topicSuggestion').on('click',function (e) {
var value = {{ object.suggestion.topic.id }};
$('#id_topic').val(value).trigger('change');
});
});
</script>
This isn't quite working as expected though. Instead of nicely populating the value, this is the behaviour I see:
- Click the link, nothing happens
- Select a random value from the list, and click the link. The select seems to clear
- Select the desired value once, now click a random value and click the link. Now the value populates correctly
I can imagine this is related to my non-existing js skills. Could someone be kind enough to help me clear this up on this newyears day?
As we can see in https://github.com/codingjoe/django-select2/discussions/145 the items are loaded async. So if you want to pre-populate, you need to add the value first.
The select2 docs explain this: https://select2.org/programmatic-control/add-select-clear-items#create-if-not-exists
The answer in this case is: