Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - how to select dropdown item based on value

I want set a dropdown(select) to be change based on the value of the entries.

I have

<select id="mySelect">   <option value="ps">Please Select</option>   <option value="ab">Fred</option>   <option value="fg">George</option>   <option value="ac">Dave</option> </select> 

And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?

like image 933
Mark W Avatar asked Jan 05 '12 14:01

Mark W


People also ask

How do I select a specific value in a Dropdownlist using jQuery?

With jQuery, it's easy to get selected text from a drop-down list. This is done using the select id. To change the selected value of a drop-down list, use the val() method.

How do I get the selected value of dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do I get the selected value of multiple dropdowns in jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.

How do I get the text value of a selected option jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").


2 Answers

You should use

$('#dropdownid').val('selectedvalue'); 

Here's an example:

$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id='dropdownid'>     <option value=''>- Please choose -</option>     <option value='1'>1</option>     <option value='2'>2</option>     <option value='selectedvalue'>There we go!</option>     <option value='3'>3</option>     <option value='4'>4</option>     <option value='5'>5</option> </select>
like image 157
Jeaf Gilbert Avatar answered Oct 13 '22 03:10

Jeaf Gilbert


$('#yourdropddownid').val('fg'); 

Optionally,

$('select>option:eq(3)').attr('selected', true); 

where 3 is the index of the option you want.

Live Demo

like image 34
xbonez Avatar answered Oct 13 '22 02:10

xbonez