$('#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); });
Leave a reply