Search code examples
jqueryjquery-select2-4jquery-select2

Multiple select element using select2 does not work properly


Please note that this is not about <select> element with multiple attribute, but multiple <select>s in a form, which I haven't found asked here.

See this codepen

I have two <select> element with unique ids and names. On both element I've also used select2. I was expecting the two would have initiated the same behavior hence the same jQuery code. The two did start the select2 but the later was not showing any option included in the <option> tags. It only shows the "No result found" message.

Question : I am pretty sure this one is pretty trivial, but can anyone show me what is wrong with the code? How is it supposed to be written?

Here is the html :

<form action="" method="POST" role="form">
  <div class="form-group">
    <label for="">Add Service Name</label>
    <select class="form-control select2" name="test-1" id="number1">
      <option>Service 1</option>
      <option>Service 2</option>
    </select>
  </div>
  <div class="form-group">
    <label for="">Add Service Name</label>
    <select class="form-control select2-service-package" id="number2" name="test-2">
      <option>Service 1</option>
      <option>Service 2</option>
    </select>
  </div>
  <button type="submit" class="btn btn-primary">Create</button>
</form>

And here is the jQuery code

  if ($('.select2-service-package').length > 0) {
    $('.select2-service-package').select2();
  };

  if ($('.select2').length > 0) {
    $('.select2').select2();    
  };

Solution

  • Try to change the name of the class select2 to something else (e.g. myselect).

    Select2 plugin probably uses the select2 class internally.

    Working example: https://jsfiddle.net/6pnv3v58/