Home / Snippets / How to get Select2 Values for Both Single and Multiselect
How to get Select2 Values for Both Single and Multiselect cover

How to get Select2 Values for Both Single and Multiselect

610

2 years ago

0 comments

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);
  });
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this