Change the selected value of a drop-down list with jQuery

Given a drop-down list, we have to change the selected option by using its value with jQuery.
Submitted by Pratishtha Saxena, on August 26, 2022

A drop-down list is a way of displaying content in an ordered & organized form, select tag (<select>) in HTML allows the user to create a drop-down menu. The options for it are declared using the option tag (<option>). This option tag takes in different attributes, like, value, id, name, etc. Therefore, each option of the select element can have different values.

These options of the drop-down list are selected by the user by clicking on the respective option. But these options can also be selected using jQuery. Here, the option will be selected using its value. For this, we'll be using the .val() method.

Using .val() Method

This method is a very useful tool in jQuery. It helps to get or set the value of the selected element. Over here, it can help us to change the selected value of the drop-down list.

Syntax:

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

The element is selected using the selector and the value to be selected has to be pre-defined. We'll consider an example where when the button is clicked, it selects the specified option by using its value as a reference. The example using .val() method is given below.

Example to change the selected value of a drop-down list with 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>Change The Seleted Value of Drop-Down List Using jQuery</h2>
    <label>Week Days: </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>
    <br><br>
    <button type="button" id="button1">Select Sunday</button>    
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            $('#mySelect').val('Seven');
        })
    });
  </script>
</html>

Output:

Example: Change the selected value of a drop-down list





All jQuery Examples

Comments and Discussions!

Load comments ↻





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