skip to Main Content

Why bootstrap selectjs is not working for dynamically appended value.

whenever i append new option from javascript it is not reflected to the live search.

below is code snippet

setTimeout(function(){
  $('#demo').append('<option>India</option>');
  console.log('appended');
},1000);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>

<select id="demo" class="selectpicker" data-live-search="true" >
    <option>Alabama</option>
    <option>Alaska </option>
    <option>Arizona </option>
</select>

2

Answers


  1. Use refresh method to refresh the picker with your new appended option.

    $('#demo').selectpicker('refresh');
    

    Reference:

    https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerrefresh

    Login or Signup to reply.
  2. Your approach is appending the new option the list need to be refreshed after appending new element.Also note there is a display:none set to default HTML select tag

    DOM view aftre appending new option

    setTimeout(function() {
      $('#demo').append('<option>India</option>').selectpicker('refresh');
      console.log('appended');
    }, 1000);
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>
    
    <select id="demo" class="selectpicker" data-live-search="true">
        <option>Alabama</option>
        <option>Alaska </option>
        <option>Arizona </option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search