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).
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");