How to get multiselect parameters of Form::select method in jquery?

Updated: Feb 04, 2025

How to get multiselect parameters of Form::select method in jquery?

To get the selected values from a multiselect parameter using jQuery with Laravel's Form::select method, you need to follow these steps:

  1. First, you need to modify the Form::select method to create an array of selected values instead of a single value. You can achieve this by setting the multiple attribute to true and giving the select element an ID.
{!! Form::select('example[]', $options, old('example') ?: [], ['multiple' => true, 'id' => 'example-select']) !!}
  1. Next, you need to use jQuery to get the selected values from the select element. You can use the val() method to get the value of a single selected option, but since we're dealing with multiple selections, we need to use the map() function to convert the selected options into an array.
$('#example-select').on('change', function() {
    var selectedValues = $(this).val();
    selectedValues = $.map(selectedValues, function(value) {
        return value;
    });

    console.log(selectedValues);
});

This code attaches an event listener to the select element with the ID 'example-select'. When the selection changes, it gets the selected values using the val() method, converts them to an array using the map() function, and logs the array to the console.

  1. Optionally, you can also get the labels of the selected options instead of their values by using the find('option:selected') method to get the selected option elements, and then using the text() method to get their labels.
$('#example-select').on('change', function() {
    var selectedValues = [];
    var selectedLabels = [];

    $(this).find('option:selected').each(function() {
        selectedValues.push($(this).val());
        selectedLabels.push($(this).text());
    });

    console.log(selectedValues, selectedLabels);
});

This code gets the selected option elements, iterates through them using the each() function, pushes their values to the selectedValues array, and their labels to the selectedLabels array. The code then logs both arrays to the console.