Select2 drop down change event not working

别来无恙 提交于 2019-12-14 03:45:45

问题


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.



来源:https://stackoverflow.com/questions/44735337/select2-drop-down-change-event-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!