Select2 drop down change event not working

2019-06-24 03:26发布

问题:

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?

回答1:

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

$("#id").on("change", function () { debugger; });


回答2:

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



回答3:

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


回答4:

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.