Reputation: 1718
I have a Bootstrap Select picker that I have to create and add to the page's HTML dynamically, after it's been loaded. The problem is that, when I do this, the selectpicker's "change" event doesn't seem to be triggered.
Here is my jsFiddle: http://jsfiddle.net/83k458Lz/7/
(Eventually, the data in the dropdown will be loaded through JSON, but in the example I have added it inline).
The code is here:
//The jsFiddle has a much more complete list of data
var lista_pueblos=[{"id":"2","nombre":"Madrid"},{"id":"4","nombre":"Barcelona"},{"id":"5","nombre":"Heidelberg"},{"id":"6","nombre":"Dusseldorf"}];
var dropdown='<select id="localidad_origen_1" name="localidad_origen_1" class="form-control selectpicker input-sm localidad_origen" data-live-search="true" required><option value="" selected disabled>Seleccione localidad</option></select>';
$("#formulario").after(dropdown);
rellenaPueblos($("#localidad_origen_1"), -1);
$('.selectpicker').selectpicker();
$('.selectpicker').refresh();
$("body").on('change',".localidad_origen, .localidad_destino", function(){
alert("Meeept");
});
function rellenaPueblos(dd, pueblo_anterior) {
var cadena="";
var elProximoEsElBueno=false;
for (var i = 0; i < lista_pueblos.length; i++) {
if (elProximoEsElBueno == true) {
cadena += "<option SELECTED value='" + lista_pueblos[i]["id"] + "'>" + lista_pueblos[i]["nombre"] + "</option>\n";
elProximoEsElBueno = false;
}
else {
cadena += "<option value='" + lista_pueblos[i]["id"] + "'>" + lista_pueblos[i]["nombre"] + "</option>\n";
}
if (lista_pueblos[i]["id"] == pueblo_anterior) {
elProximoEsElBueno=true;
}
}
//alert(dd.name);
dd.append(cadena);
}
And the HTML is very simple:
<form id="formulario">
</form>
As you can see, the dropdown gets populated correctly, but when I pick an option, the "change" event doesn't seem to be triggered. I have read about event delegation, but as you can see, the event handler is attached to body
. to take advantage of event bubbling.
What else am I missing? I have the suspicion that it must be something really silly...
Upvotes: 3
Views: 8803
Reputation: 1870
Change this:
$('.selectpicker').refresh();
To this:
$('.selectpicker').selectpicker('refresh');
Calling the non-existent refresh() method prevented the remaining code from being executed.
Corrected fiddle: http://jsfiddle.net/BenjaminRay/83k458Lz/11/
Upvotes: 4