I'm using Silvio Moreto's Bootstrap Select.
On my page I have a button that opens a modal with an input box that allows you to add an item to the selectpicker. I would then like to automatically have that item selected but I can't get it to work.
The code I have is :
$('#myselect').append('<option val="'+newitemnum+'">'+newitemdesc+'</option>'); $('#myselect').val(newitemnum); $('#myselect').selectpicker('refresh');
But it just doesn't work. The item doesn't get selected.
I have tried replacing the selection line with :
$('#myselect').selectpicker('val',newitemnum);
but that doesn't work either
Any ideas much appreciated (although the item DOES get added to the selectpicker).
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.
selectpicker('mobile') . This enables the device's native menu for select menus. The method for detecting the browser is left up to the user.
selectpicker("destroy"); $('select#pause' + _week + _day). selectpicker("destroy"); In other plugins if you use destroy, it shows the original element again. Is this an issue in the boostrap select plugin or is there another way to remove the bootstrap select and reshow the original select.
You have a typo. Instead of:
$('#myselect').append('<option val="'+newitemnum+'">'+newitemdesc+'</option>');
You need:
$('#myselect').append('<option value="'+newitemnum+'">'+newitemdesc+'</option>');
Here is a JSFiddle demo: http://jsfiddle.net/xbr5agqt/
The "Add and select 'Soy Sauce' option" button does the following:
$("#myselect").append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); $("#myselect").val(4); $("#myselect").selectpicker("refresh");
One slightly faster approach (used by the "Add and select 'Relish' option" button) is to append the new <option> element with the selected
attribute already applied:
$("#myselect").append('<option value="'+newitemnum+'" selected="">'+newitemdesc+'</option>'); $("#myselect").selectpicker("refresh");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With