Select2 drop down change event not working
Asked Answered
D

8

11

I am using Select2 drop down and I need to do some functionalities based on the the drop down selection.

I have tried the following code, but it didn't worked for me.

$eventSelect.on("select2:select", function (e) { log("select2:select", e); });

$eventSelect.on("change", function (e) { log("change"); });

Can anyone tell me how can I make this work?

Drue answered 24/6, 2017 at 10:17 Comment(1)
Did you try to include the function code I included in my answer? What was the error message that you got, if it said 'log is not defined' then it would be due to you not having including the function in your code. – Cohune
D
12

I am using select2 version 3.3.2 and the following code is working for me

$("#id").on("change", function () { debugger; });
Drue answered 27/6, 2017 at 6:20 Comment(0)
M
7

You can try declaring the event after you know the web page has fully loaded, in my case, this was the problem:

$(document).ready(function(){
    $('#yourselect').on("select2:select", function(e) { 
        console.log($(this).val());
    });
});
Meretricious answered 19/10, 2017 at 16:40 Comment(0)
C
1

Try this code

$eventSelect.select2().on("change", function(e) {
          // mostly used event, fired to the original element when the value changes
          log("change val=" + e.val);
        })
Cumbrous answered 24/6, 2017 at 10:22 Comment(0)
L
1
$(document).on('change', '.js-example-basic-single', function(e) {
console.log($(this).val());})
Lethe answered 12/10, 2021 at 13:14 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – Superabound
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck πŸ™‚ – Premillennialism
C
0

I can see that you took your code from the select2 documentation:

https://select2.github.io/examples.html#programmatic-control

Did you notice that they define a function below that code is using called log().

Here is the function code, did you include that also?

function log (name, evt) {
  if (!evt) {
      var args = "{}";
  } else {
      var args = JSON.stringify(evt.params, function (key, value) {
      if (value && value.nodeName) return "[DOM node]";
      if (value instanceof $.Event) return "[$.Event]";
      return value;
      });
  }
  var $e = $("<li>" + name + " -> " + args + "</li>");
  $eventLog.append($e);
  $e.animate({ opacity: 1 }, 10000, 'linear', function () {
      $e.animate({ opacity: 0 }, 2000, 'linear', function () {
          $e.remove();
      });
    });
}

Alternatively you could use console.log() to output to the console.

Cohune answered 24/6, 2017 at 10:25 Comment(5)
I am not using the log method still it is not working. – Drue
Your code does use the log function it's called on both lines in your answer. Try including this code in my post on your page. What was the error in the browser? – Cohune
Actually I am not using the log method in my code, My code is some thing like this, $eventSelect.on("select2:select", function (e) { debugger; }); $eventSelect.on("change", function (e) { debugger; }); and there is no error at all , the problem is that the debugger is not hitting when i change the dropdown selection. – Drue
You see how twice in your code it's says log(...) That is calling the log function. There must be a function in your code called log for that to work. Have you tried adding the code in my answer? What is your error message? – Cohune
It might have been better to post up all of your actual code, better still if you could include a link to an example. The code you posted is the correct way to check for the select2 events for version 4+ . I know that prior to version 4 the API is very different, although I'm not sure about the events. What version are you using, are you looking at the correct documentation? – Cohune
A
0

With select2 version 4 the events have changed. This is an old version example

$('#exampleVersionOld').select2().on('change', function(item){
    ...
});

And here is a new version example

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

Note the structure of the item also changes with this new event.

Here is a list of all the new events

https://select2.org/programmatic-control/events

Arium answered 15/6, 2022 at 14:27 Comment(0)
S
0

As of version 4.0.0, Can use the following events:

Reference: https://select2.org/programmatic-control/events

select2:close
select2:open
select2:opening
select2:selecting
select2:removed
select2:unselecting

For Example:

(function($){
  $('.select2').select2();
  
  $('.select2').on('select2:selecting', function(e) {
    console.log('Selecting: ' , e.params.args.data);
  });
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>



<select class="select2">
  <option>Volvo</option>
  <option>Saab</option>
  <option>Mercedes</option>
  <option>Audi</option>
</select>
Silvester answered 6/12, 2022 at 15:6 Comment(0)
T
0

One common issue is ensuring that the data being returned by the AJAX call is correctly structured and accessible. Here is the updated JavaScript.

$(document).ready(function() {
$('#search').select2({
    placeholder: 'Search for an item',
    ajax: {
        url: '{{ route('search') }}', // Ensure this is the correct route
        dataType: 'json',
        delay: 250,
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        id: item.id,
                        text: item.name,
                        name: item.name,
                        email: item.email
                    }
                })
            };
        },
        cache: true
    }
});

$('#search').on('select2:select', function (e) {
    var data = e.params.data; // Access the data directly
    $('#customer-name').val(data.name);
    $('#customer-email').val(data.email);
});
});

in the Controller

public function customers(Request $request)
{
    $search = $request->get('q');
    $data = Customer::where('name', 'LIKE', "%{$search}%")->limit(10)->get();
    return response()->json($data);
} 
Treadwell answered 18/6, 2024 at 6:59 Comment(0)

© 2022 - 2025 β€” McMap. All rights reserved.