Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append options in select bootstrap?

My select bootstrap dosn't show the options i append:

This is the index:

<div class="form-group label-floating">
  <div class="row">
    <div class="col-lg-5 col-md-6 col-sm-3">
      <select id="recau_agente" class="selectpicker" data-style="btn btn-primary btn-round" title="Single Select" data-size="7">
      </select>
    </div>
  </div>
</div>

This is the jQuery to insert the options in the select:

var ruta = "https://maxtechglobal.com/vencimientos/arba/conceptos_recaudacion.php";
var $select = $('#recau_agente');
$.getJSON(ruta, function(json) {
  $select.html('');
  $.each(json.data, function(index, value) {
    $select.append('<option id="' + value.concepto + '">' + value.concepto + '</option>');
  });
});
like image 760
Agustín Osorio Avatar asked Nov 29 '22 09:11

Agustín Osorio


1 Answers

I see what you mean, what you really need is to call refresh after you get the data and finish updating the select option. So add the following after the .each (since each is synchronous so no need for call back, just put the refresh after the .each will work)

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

#.selectpicker('refresh')

To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.

REF: https://silviomoreto.github.io/bootstrap-select/methods/

$(document).ready(function() {
  var ruta = "https://maxtechglobal.com/vencimientos/arba/conceptos_informacion.php";
  var $select = $('#select');
  //init
  $('.selectpicker').selectpicker({
    style: 'btn btn-primary btn-round'
  });

  // arma el ajax de la variable ruta con una funcion incorporada
  $.getJSON(ruta, function(json) {
    // vacia el select
    $select.html('');
    // cada array del parametro tiene un elemento index(concepto) y un elemento value(el  valor de concepto)
    $.each(json.data, function(index, value) {
      // darle un option con los valores asignados a la variable select
      $select.append('<option id="' + value.id+ '">' + value.impuesto+ '</option>');
    });
    $('.selectpicker').selectpicker('refresh');
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/css/bootstrap-select.min.css">

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/bootstrap-select.js"></script>

<select id="select" class="selectpicker" data-style="" title="Single Select" data-size="15"></select>
like image 188
Dalin Huang Avatar answered Dec 08 '22 00:12

Dalin Huang