Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  132] [ 2]  / answers: 1 / hits: 70095  / 9 Years ago, sat, october 17, 2015, 12:00:00

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


More From » jquery

 Answers
5

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

[#64702] Thursday, October 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yaquelina

Total Points: 517
Total Questions: 101
Total Answers: 96

Location: Egypt
Member since Tue, Jul 6, 2021
3 Years ago
yaquelina questions
;