Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap-select add item and select it

Tags:

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

like image 967
Chris Jones Avatar asked Oct 17 '15 19:10

Chris Jones


People also ask

How do I append to bootstrap select?

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.

What does selectpicker do?

selectpicker('mobile') . This enables the device's native menu for select menus. The method for detecting the browser is left up to the user.

How to destroy selectpicker?

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.


1 Answers

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"); 
like image 69
Daniel Trebbien Avatar answered Oct 03 '22 23:10

Daniel Trebbien