Posts Learn Components Snippets Categories Tags Tools new About
/

How to get Select2 Values for Both Single and Multiselect

Learn how to get select2 values for both single and multi select input and perform some logic after retrieving the value

Created on Nov 04, 2021

16 views

To get the select2 values (single and multi-select) it's fairly simple and straightforward. For starters, you can make use of the ".val()" to retrieve the value of the selected option.
$('#select2-input').val();

Using Data Method


Another way is to use the "data" method and this will return a JavaScript array of objects representing the current selection.
$('#select2-input').select2('data');

Using jQuery Selector


Lastly, you can use the jQuery selector and once you have the value you can right away perform any action.
$('#select2-input').find(':selected');

Select2 With Axios for Backend Ajax


Sometimes you might also want to right away call an Ajax and pass the value of the select2 as the parameter. To easily make a backend Ajax request you can make use of Axios HTTP library and for the parameters, you can pass in the select2 value that is retrieved using ".val()" like the code example below.
axios.post('/post-action', {
    action: $('#select2-input').val()
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)