Search code examples
javascriptjquerydataframeflaskbootstrap-selectpicker

How can I reorder the selection of selectpicker based on my user selection?


I am planning to implement a selectpicker, which will allow user to choose multiple options from the dropdown list. The catch is that when my backend extract the values from this selectpicker, the values must be in the sequence of the user selection and not the order of the original dropdown list. Hope to get some help on this! Thanks a lot in advance!

I am developing this with django (Frontend) and Flask(backend)

Planning to populate the selectpicker with values from my DataFrame

Let say the sequence of options in the selectpicker is like the following:

  1. A
  2. B
  3. C
  4. D

So, when user select the options in the following sequence, D, A, C

Expected value extraction from this selectpicker element: D, A, C

Undesired value extraction from this seelctpicker element: A, C, D


Solution

  • This can be done by simply pushing a selected element to an array of strings. You just have to make sure to remove it from the array again if the user has decided to deselect that option. The array push() method will make sure that a newly selected item will always be the last element thus keeping the correct order.

    var myChoices = new Array();
    $('#myPicker').on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue) {
      var selected = document.getElementById("myPicker").options[clickedIndex].value;
      if (myChoices.indexOf(selected) == -1) {
        myChoices.push(selected);
      } else {
        myChoices.splice(myChoices.indexOf(selected), 1);
      }
      console.log(myChoices);
    });
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.9/dist/css/bootstrap-select.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.9/dist/js/bootstrap-select.min.js"></script>
    <select class="selectpicker" id="myPicker" multiple>
      <option>TV</option>
      <option>Radio</option>
      <option>Newspaper</option>
    </select>