1

I have a bootstrap select which i want to change the value programmatically. Something just like:

<select class="form-control selectpicker" id="testpicker" data-lastselected="Ketchup">
 <option>Mustard</option>
 <option selected="">Ketchup</option>
 <option>Relish</option>
</select>

To change it i use the following function:

$('#testpicker').selectpicker('val', value to change);

And i'm listening to it's change with:

$('select').on("change", function() {}

Inside the change function i've a if statement asking the user if he really wants to change the option and proceed with the process:

 if (!confirm("Sure you want to change to " + $('#testpicker').val())) {
    $('#testpicker').selectpicker('val', 
    $('#testpicker').data('lastselected'));
 } else {
    $('#testpicker').data('lastselected', $('#testpicker').selectpicker('val'));
 }

So, when the users response to the confirm is cancel, the bootstrap-select enters in a infinite loop, always showing the confirm dialog until the users accept it!

You can check it here.

Solution i've used to workaround this behaviour - to change the value use:

$('#testpicker').val(value to change).selectpicker('refresh');
  • as you can see [here](https://jsfiddle.net/edwpcmo0/1/) it works. Take a look to the libraries and run your code on document ready – gaetanoM Sep 15 '18 at 13:58
  • Possible duplicate https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript – Llazar Sep 15 '18 at 14:33
  • I didn't make myself explained, i'll rephrase the question! – Pedro Magalhães Sep 17 '18 at 07:09

0 Answers0