ScanQR
ScanQR

Reputation: 3820

Set Selecpicker val and set option as selected dynamically

Question metadata

Bootstrap selectpicker version : Selectpicker.VERSION = '1.7.2';

jQuery version : jQuery JavaScript Library v1.11.2

Problem statement :

I have a filter select list. On selecting an option (a filter), server responds with entire filter details. Based on returned data, I need to set couple of select elements (bootstrap selects). Once the value is set I also need to set that option as selected.

Selects Elements Markup (all have distinct id's)

<select id="pspName" class="form-control selectpicker"> <!--Options --> </select>
<select id="pmName" class="form-control selectpicker"> <!--Options --> </select>
<select id="countryName" class="form-control selectpicker"> <!--Options --> </select>
.
.
.
<select id="currencyName" class="form-control selectpicker"> <!--Options --> </select>

jQuery code :

Selecpicker initialization works well :

 //all at once.
 $('.selectpicker').selectpicker();

Code tried but with no luck. So require assistance for the same is as follows,

I tried with usual conventions of find option by value but it did not work well, e.g. for select with id as pspName get option by value and trigger click. But it failed to refresh the select and it is also not set to selected.

 $('select#pspName option[value="server_returned_value"]').click();

Upvotes: 3

Views: 1196

Answers (1)

R.Costa
R.Costa

Reputation: 1393

You must use a specific method to set the values:

$('#countryName').selectpicker('val', 'Japan');

I've created a small example to setup several elements based on a set of attributes :

JSFIDDLE

Upvotes: 1

Related Questions