Last Updated on September 4, 2022 by Roshan Parihar
In this tutorial, you will learn how to set value of select dropdown option using jQuery. The short answer is to use the val()
and pass the value as its arguments to assign.
When you know the required value from the select dropdown options, you can select that option using jQuery. Let’s find out the different methods with the examples given below.
Method 1: Set Value of Select Option Using val()
To set the value of the select option using jQuery, you can use the val()
function that takes a single argument. The argument is the required value of the select dropdown to specify and select. You can add the value as an argument within the quotes (' '
).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('button').click(function(){ var myval = 'red'; $("select").val(myval); }); }); </script> <select> <option value="">Select your option</option> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <button type="button">Set Select Value</button> |
Output
The above example contains the select dropdown with three options to select. The specified value to get selected using jQuery is ‘Red’. When you click the button element, the specified value gets selected using jQuery.
Method 2: Using attr()
Function of jQuery
In addition to the above example, you can also use the attr()
that takes two arguments to pass and select the dropdown option. Both the first and the second argument of the function are 'selected'
.
To specify the value, you have to use the jQuery selector code snippet $("select option[value=myvalue]")
before the attr()
. Also, don’t forget to replace the myvalue
with your specific value to set the value of the select option.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('button').click(function(){ var myval = 'Two'; jQuery("select option[value="+myval+"]").attr('selected', 'selected'); }); }); </script> <select> <option value="">Select your option</option> <option value="One">One</option> <option value="Two">Two</option> <option value="Three">Three</option> </select> <button type="button">Set Select Value</button> |
Output
The above example contains a dropdown with three options. The example specifies the value ‘Two’ to select on button click. With a click of the button, jQuery sets the specified value of the select dropdown option.
You May Also Like to Read