Search code examples
javascriptjqueryhtmljquery-select2-4

how to trigger event on select2


hi guys i have some select tags in my selling item page. first one created by HTML and others are created by jquery append when user click on a button add more

<select id='code0' onclick='getvalue(this)'><option>1</option></select>

and in document.ready im applying select2 on this select tag

$(document).ready(function(){
 $("#code0").select2();
})


function append(){
  $("table").append("<tr><td><select id='code1' onclick='getvalue(this)'><option>1</option></select></td></tr>");
  $("#code1").select2();
}

next appended select will have id of code2. I'm managing it without any issue

Now the function getvalue() is working fine before applying select2 but after applying select2 the select is not triggering click or any event. how can i trigger event after applying select 2;

function getvalue(item){
  alert("event triggered"); // to check that jquery called this function or not
  console.log(item.value);
}

clicking on select tags is not calling get value function;

whenever the page loads i can see this error on console

jQuery-2.1.4.min.js:2 Uncaught TypeError: Cannot read property 'call' of null
    at Function.each (jQuery-2.1.4.min.js:2)
    at MutationObserver.<anonymous> (select2.min.js:2)

Solution

  • Once you have linked select2 to existing select.

    select2 override select and create list(li) for all options and select is hidden.

    So any event added to select will not work directly.

    Select2 plugin provides functions which you can use to server your need

    Assign select2 ele as a var and use methods given by plugins

    var select2Ele = $("#code0").select2();
    
    select2Ele.on("select2:select", function (event) {
       // after option is selected 
    });
    
    select2Ele.on("select2:selecting", function (event) {
       // before selection 
    });
    

    For multiple select2 above code will work like this. In log method we have event which can be used to get current element value and other stuffs

    $eventSelect.on("change", function (e) { log("change"); });
    
    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();
        });
      });
    }
    

    Refer select2 doc