I'm using SnapAppointments bootstrap-select (https://github.com/snapappointments/bootstrap-select/) and get the following strange behavior (maybe a bug?).
When the page is loaded, the option
s are updated, the desired value is set, but when I try to retrieve it later (demonstrated by a delay), it is lost.
The problem seems to be the title
attribute (set either as title
, data-title
or by script); to make it easier to play with the fiddle I left the script version. See line #10 of the script.
Simply put, when there's a title
set, the value is lost... And I kind of need the title.
var jData = {"data":[
{"label":"Option 1","value":"1"},
{"label":"Option 2","value":"2"},
{"label":"Option 3","value":"3"},
{"label":"Option 4","value":"4"},
{"label":"Option 5","value":"5"}]
};
// comment / uncomment this line to reproduce the problem
$('#test').attr('title', 'test title');
// simulate a dynamic data load
$('#test').find('optgroup').remove();
$('#test').find('option').remove();
jData.data.forEach(function (o) {
o.option = $('<option/>').attr('value', o.value).text(o.label).appendTo($('#test'))[0];
});
$('#test').selectpicker('destroy').selectpicker().selectpicker('val', '2');
console.log('value after selectpicker(\'val\', \'2\') : ' + $('#test').val());
$('#test').find('option[value=2]').attr('selected','selected');
console.log('value after attr(\'selected\',\'selected\') : ' + $('#test').val());
window.setTimeout(function() {
console.log('value after delay : ' + $('#test').val());
}, 1000);
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>
<select id="test" name="test" data-live-search="true" >
<button id="load" >Load data</button>
Any help is appeciated.
The solution to this issue came from github (posted the question there, too), from user AdrienGiboire
; I'm posting it here too in the hope it will help :
It happens because you call
destroy
So the correct approach is not to :
$('#test').selectpicker('destroy').selectpicker().selectpicker('val', '2');
but
$('#test').selectpicker().selectpicker('val', '2');
And only call $('#test').selectpicker('destroy');
if really needed.
Credit for the solution goes to the github user AdrienGiboire