V.V
V.V

Reputation: 31

How to get current selected value of Multiselect Dropdown or Select2 Dropdown?

I have a requirement to show a popup when (Multiselect or Select2) Dropdown is selected if the selected dropdown value having a "YES" value in db. I Posted a ajax call having the ID of current selected value of the dropdownlist.

Am getting values as array type, I need to get a value of the particular option which is selected by User. So that I will check that value having "YES" value in DB,

The problem is : Am getting value always as first selected item.

I Have tried these steps:

var id =

Upvotes: 2

Views: 6213

Answers (3)

remonses
remonses

Reputation: 412

@Muhammad Omar Aslam's answer is right.

But for older versions of select2, the event is not fired.

You can then use something like this:

$('#mySelect2').on('change', function (e) {
  var data = e.currentTarget.value
  console.log(data);
});

Upvotes: 0

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

You should use the events provided by select2 Event Docs

$('#mySelect2').on('select2:select', function (e) {
  var data = e.params.data;
    console.log(data);
});

So if you click on yes assuming that you have your select drop-down options like

<option value="yes">Yes</option>
<option value="no">No</option>

it will show you in the console like below

{
  "id": yes,
  "text": "Yes",
}

so you can do like

$('#mySelect2').on('select2:select', function(e) {
  var data = e.params.data;
  if (data.id == 'yes') {
    //send your ajax call
  } else {
    //do something else
  }
});

hope this helps

Upvotes: 3

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

This will get the selected values in an array, which you can then pass to your server-side code to check the database. It may be more suitable to pass the relevant data to your page and do the check there, but without knowing more about the scenario I'll leave that up to you.

Here's the code...

$("#mySelect").on("change", function() {
  console.log($(this).val());  // contains an array of ID
});
select {
  height: 100px;
  width: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="mySelect" multiple>
    <option value="id1">option 1</option>
    <option value="id2">option 2</option>
    <option value="id3">option 3</option>
    <option value="id4">option 4</option>
    <option value="id5">option 5</option>
</select>

Upvotes: 0

Related Questions