2
votes

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 =

  • $(".select2 option:selected").val();
  • $(this).val();
  • $(this).find('option:first').next().val();
  • $(this).last().val();
3
do select the answer that worked for you so others having the same issue might also benefitMuhammad Omer Aslam

3 Answers

3
votes

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

0
votes

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>
0
votes

@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);
});