×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery - Get value of select onChange

Given a drop-down, we have to get the value of selected option using jQuery.
Submitted by Pratishtha Saxena, on August 25, 2022

Select tag (<select>) in HTML allows 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 selected element can have different values.

Now, let's discuss how to access these values when the user selects the option? Hence, we cannot predefine the value of the option tag in our jQuery function. This value has to be taken when the user selects the option. This task can be done using the find() method of jQuery.

This, find() method helps to find the value specified within the brackets. In other words, it helps to get the descendants of the selected element.

Syntax:

$(selector).find(filter);

Over here, the filter we'll use is the :selected property. Since we don't know the value of the option, hence, this property will help us to get the value of the selected option.

Syntax:

$(selector).find(':selected');

Till here, we have figured out how to find the selected option using jQuery. Now, to find the value of the option, val() method will be used which will help to get the value of the selected element.

Syntax:

$(selector).val();

These all methods, when used together will return the value of the selected option. The following example shows the same. The value of the selected option will appear below the drop-down as soon as a new option is selected.

Example to get value of select onChange using 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 data-name="John">Select Elements By Data Attributes</h2>
    <div id="myDiv" data-name="Tom" data-age="20">Welcome to Include Help !!</div>
    <p data-name="Harry">jQuery Tutorial</p>
    <button type="button" id="button1">Click Here</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            var name = $('[data-name = "Tom"]').data('name');
            alert(name);
    
        });
    });
  </script>
</html>

Output:

Example 1: Get value of select onChange

After selecting the element

Example 2: Get value of select onChange





Comments and Discussions!

Load comments ↻





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