jquery get multiple selected option value

JQuery - Get Multiple Selected Option Value

If you are working with HTML forms and you have a select element with multiple options, you might need to know how to get the values of the selected options. JQuery makes it easy to do this in just a few lines of code.

Method 1: Using .val()

The .val() function in JQuery can be used to get the value of the selected options in a select element. Here is the code:


      var selectedValues = $('#mySelect').val();
    

In the above code, "mySelect" is the id of the select element. The .val() function returns an array of selected option values. If no option is selected, it returns null. If you want to get the text of the selected options instead of their values, you can use .text() function instead.

Method 2: Using .each()

The .each() function in JQuery can be used to loop through each selected option in a select element and get its value. Here is the code:


      var selectedValues = [];
      $('#mySelect option:selected').each(function() {
        selectedValues.push($(this).val());
      });
    

In the above code, we start by creating an empty array called selectedValues. We then use the #mySelect option:selected selector to get all selected options in the select element. We then loop through each selected option using the .each() function and push its value into the selectedValues array. Finally, we have an array of all selected option values.

Method 3: Using .map()

The .map() function in JQuery can also be used to loop through each selected option in a select element and get its value. Here is the code:


      var selectedValues = $('#mySelect option:selected').map(function() {
        return $(this).val();
      }).get();
    

In the above code, we start by using the #mySelect option:selected selector to get all selected options in the select element. We then use the .map() function to loop through each selected option and return its value. Finally, we use the .get() function to convert the result into an array of selected option values.

These are some of the ways you can get the values of multiple selected options in a select element using JQuery. Choose the one that works best for your situation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe