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

544

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

Ahmad Aziz

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 ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this