jQuery
jQuery Set Dropdown Value Examples
If you are wondering how to use jQuery to set dropdown value using jQuery, then look no further! In this article, I am going to share some examples that show how to easily set dropdown value.
How to use jQuery to Set Dropdown Value
The following is the HTML source code of the example. It assumes that there is a dropdown box with ID “country” and the value of the dropdown needs to be set to a different value when a button is clicked.
Common HTML Code for all following examples:
<html> <head> <title>jQuery Set Dropdown Value | Set Dropdown Value using jQuery Examples</title> <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script> </head> <body> <select name="country" id="country"> <option value="Australia">Australia</option> <option value="London">London</option> <option value="USA">USA</option> </select> <input type="submit" name="set" id="set" value="Set USA as country" /> </body> </html>
Example 1: Set Dropdown Value using val() method using jQuery
<script type="text/javascript">
$('#set').click(function() {
$("#country").val("USA");
});
</script>Example 2: Set Dropdown Value using attr selectedIndex using jQuery (Works only when jQuery version < 1.6)
<script type="text/javascript">
$('#set').click(function() {
$("#country").attr('selectedIndex', 2);
});
</script>Example 3: Set Dropdown Value using attr selectedIndex using jQuery (Works only when jQuery version >= 1.6)
<script type="text/javascript">
$('#set').click(function() {
$("#country").prop('selectedIndex', 2);
});
</script>That’s it!
Do you know of any other ways to set dropdown value using jQuery? Feel free to suggest by commenting below.