javascriptjqueryselect2-rails

Why won't this delegated version of jQuery's .on work right?


When I run this code, I do not get the simple alert. I delegated it to the body because the element does not exist in the DOM on page load, it is dynamically generated after clicking on a dropdown via https://github.com/argerim/select2-rails.

$(document).ready(function(){
  $('body').on('click', ".select2-highlighted", function() {
    alert("derp");
  });
});

As always, I appreciate any help! Even telling me I suck and to re-read the docs and troubleshoot it more! But please no downvotes without giving me some advice :/

EDIT

Sorry everyone, I did not know that the select2 library I was using had events that I could bind to. I just started my job a few months ago and inherited a large codebase, part of which is select2, so I dug into the docs today.

Thanks again to Pointy, A. Wolff, Kresimir Pendic, charlietfl for getting me started down the road to the fix!


Solution

  • This worked for me in the past (for dinamicaly added forms) that I attached select2 component on

    $( elem ).on( 'select2-open', function(){ // ... });
    

    so I guess if you are on version 3.x and not new v4 that you can similary do:

    $( elem ).on( 'select2-highlight', function(){ //.. });
    

    here is the page that has that event documented: http://select2.github.io/select2/