[Answered ]-Django form data modification with jquery

1👍

You don’t need to manually create li tags they are automatically created by select2 plugin whenever any value is selected .So, you just need to append new option inside your select-box then use $("#id_clients").val('somevalue') to set value as selected this will make entry inside ul tag and lastly use trigger('change') to refresh your selectbox.

Demo Code :

$(".select2-hidden-accessible").select2({
  width: '100px'
});

function addAll() {
  $('#id_clients').empty(); //empty select
  stClientId = '<option value="255">Client5</option>';
  $('#id_clients').append(stClientId); //append option
  $("#id_clients").val('255'); //set new value
  $("#id_clients").trigger('change'); //refresh select
}

$(document).ready(function() {
  $('#id_language').change(function() {
    l = $('#id_language').val();
    if (l == "ES") {
      addAll();
    }
  });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<select name="clients" id="id_language">
  <option value="li">li</option>
  <option value="ES">ES</option>
</select>
<select name="clients" id="id_clients" multiple="" class="admin-autocomplete select2-hidden-accessible">
  <option value="2355">Client1</option>
  <option value="23525">Client2</option>
</select>
👤Swati

Leave a comment