Iterate through <select> options using jQuery

In this tutorial, let’s discuss that how can we iterate through the <select> options using jQuery?
Submitted by Pratishtha Saxena, on June 26, 2022

Whenever any iterations have to be made, generally forEach(), map(), and filter() methods are used. To traverse the <select> tag, a function has to be created which will return the text, value, or both (text and value) of the options in it.

For this, each() method of jQuery will be used. Using this, elements can be traversed easily. each() method allows us to declare a function that runs for every matched element that has been traversed.

Syntax:

$(selector).each(function(index, element)); 

The function can be created in such a way that it accepts index and element as its parameters as shown.

Now, to make sure that each() method iterates all the options of the select tag, we'll have to specify the id of the select tag and then mention the option after it.

Let's see an example for a better understanding,

Example:

HTML Code:

<!DOCTYPE html>

<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
   </head>
   <body>
      <center>
         <h2>Devices</h2>
         <select id="mySelect">
            <option value="one">Laptop</option>
            <option value="two">Watch</option>
            <option value="three">Mobile</option>
         </select>
         &nbsp;&nbsp;&nbsp;
      </center>
   </body>
</html>

jQuery Function:

<script>
    $("#mySelect option").each(function() {
        console.log('Text:-' + this.text + '  Value:-' + this.value);
    });
</script>

Output:

Example: Iterate through select-options





All jQuery Examples

Comments and Discussions!

Load comments ↻





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