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?
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.
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.
With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.
$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").
$('#dropdownid').val('selectedvalue');
$('#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>
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3
is the index of the option you want.
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With