nash
nash

Reputation: 533

Updating a single bootstrap-select to multiple

I need to change a multiple bootstrap-select attribute depending on the change event of another select, but it doesn't refresh properly. The select element is successfully updated on the DOM, not the button tho.

Here is the code:

HTML

<select class="selectpicker" title="-- Select an event" id="eventType">
  <option value="1">Appointment</option>
  <option value="2">Videocall</option>
  <option value="3">Multiconference</option>
</select>

<select class="selectpicker" title="-- Select a user" id="userList">
  <option value="1">User 1</option>
  <option value="2">User 2</option>
  <option value="3">User 3</option>
  <option value="4">User 4</option>
  <option value="5">User 5</option>
  <option value="6">User 6</option>
  <option value="7">User 7</option>
</select>

JS

$('#eventType').change(function () {
    var $userList = $('#userList');

    if (this.value == 3) {
      // If type 3 is selected enable multiselect
      $userList
        .attr('title', '-- Select max. 5 users')
        .attr('multiple', true)
        .data('max-options', 5)
    } else {
      // Single select
      $userList
        .attr('title', '-- Select a user')
        .attr('multiple', true)
        .data('max-options', 1)
    }
    $userList.selectpicker('refresh');
});

DOM

<select class="selectpicker form-control" title="-- Select max. 5 users" id="userList" tabindex="-98" multiple="multiple"></select>
<button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" role="combobox" aria-owns="bs-select-2" aria-haspopup="listbox" aria-expanded="false" data-id="userList" title="-- Select a user">...</button>

Upvotes: 2

Views: 1624

Answers (1)

noamyg
noamyg

Reputation: 3104

I've made several changes to your code to make it work:

  1. If you always want to have multiple select but just change the maximum options to 1, there's really no point of doing .attr('multiple', true) on each change. For some reason, it just messes things up. Just set it to multiple in your template. That solves the problem you brought up.
  2. On change, reset your value of userList. This would make things clearer and easier.
  3. Use $userList.selectpicker({title: '...'}) to change the title, because using .attr just won't work

Here's a full working Plunker: https://plnkr.co/edit/SpSeaHTnfILDdndwpABt?p=preview

Upvotes: 2

Related Questions