Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected value on select using selectpicker plugin from bootstrap

I'm using the Bootstrap-Select plugin like this:

HTML:

<select name="selValue" class="selectpicker">    <option value="1">Val 1</option>    <option value="2">Val 2</option>    <option value="3">Val 3</option>    <option value="4">Val 4</option> </select> 

Javascript:

$('select[name=selValue]').selectpicker(); 

Now I want to set the value selected to this select when button clicked... something like this:

$('#mybutton').click(function(){    $('select[name=selValue]').val(1); }); 

But nothing happens.

How can I achieve this?

like image 604
jcvegan Avatar asked Feb 11 '13 00:02

jcvegan


People also ask

How to set selected value in selectpicker?

You can set the selected value by calling the val method on the element. $('. selectpicker'). selectpicker('val', 'Mustard'); $('.

How to use selectpicker in bootstrap?

selectpicker'). selectpicker({ style: 'btn-info', size: 4 }); }); Your script is declared and therefore executed before the <select class="selectpicker"> -declaration, causing bootstrap-select never being initialized opon . selectpicker (selectpicker doesnt exists when the script is runned).

How to refresh bootstrap selectpicker?

$('. selectpicker'). selectpicker('refresh');

What is select picker?

Select Picker is a jQuery plugin supporting work with select boxes. It extends the default possibilities of select boxes with a new range of features.


1 Answers

The value is correctly selected, but you didn't see it because the plugin hide the real select and show a button with an unordered list, so, if you want that the user see the selected value on the select you can do something like this:

//Get the text using the value of select var text = $("select[name=selValue] option[value='1']").text(); //We need to show the text inside the span that the plugin show $('.bootstrap-select .filter-option').text(text); //Check the selected attribute for the real select $('select[name=selValue]').val(1); 

Edit:

Like @blushrt points out, a better solution is:

$('select[name=selValue]').val(1); $('.selectpicker').selectpicker('refresh') 

Edit 2:

To select multiple values, pass the values as an array.

like image 84
Tom Sarduy Avatar answered Sep 28 '22 13:09

Tom Sarduy