jQuery - Set select option 'selected', by value

Learn, how can one set the options of select element as 'selected' by value using jQuery?
Submitted by Pratishtha Saxena, on August 24, 2022

Select Tag (<select>) is a very essential element used for creating drop-downs for a webpage. Select tag creates a drop-down whereas the options for the drop-down are given through the option tag (<option>). The select tag takes in various parameters as attributes like name, required, id, value, etc.

Now, what if there is a situation when you have to select an option using the value given by the option tag? Yes, we can set the option as selected using the val() method of jQuery.

jQuery val() Method

This is a jQuery built-in method. Basically, val() method can set the value attribute of any specified element, and also it can return the value of the element. Using this method, here we can have the option selected by specifying the value attribute beforehand.

Syntax:

$('selector').val('value');

This is the simplest way of selecting an option by value using jQuery.

Let's understand this better with the help of an example.

Example to set select option 'selected', by value in jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Set Select Option 'Selected' By Value </h2>
    <label>Drop-Down: </label>
    <select id="mySelect">
      <option>--Select--</option>
      <option value="one">Monday</option>
      <option value="two">Tuesday</option>
      <option value="three">Wednesday</option>
      <option value="four">Thursday</option>
      <option value="five">Friday</option>
      <option value="six">Saturday</option>
      <option value="seven">Sunday</option>
    </select>
    <button type="button" id="button1" style="margin-left: 60px;">Select Friday</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            $('#mySelect').val('five');
        });
    });
  </script>
</html>

Output:

Example: Set select option 'selected', by value






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.