Home » Jquery » javascript – Li click is not working with select2 plugin

javascript – Li click is not working with select2 plugin

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a select menu built with select2 plugin. I need to add a class to <select> when click menu options. Tested with alert it’s not working.

https://jsfiddle.net/ysm4qhof/1/

$(document).ready(function(){
$('.select2-results__option').on('click', function(){
   alert("Hello! I am an alert box!");
});
});

Tried with clicking ul but that also not working.

$(document).ready(function(){
    $('.select2 .select2-results__options').on('click', function(){
       alert("Hello! I am an alert box!");
    });
    });

It should be working but what am I missing here?

How to&Answer:

enter image description herethis is working , first change selector to js-select2 because this class name you using for select name and for select field use change function insted of click

$(document).ready(function(){
$('.js-select2').on('change', function(){
alert("Hello! I am an alert box!");
});
});

Answer:

You can use on select event of select 2 plugin.

$('.js-select2').on('select2:select', function (e) {
  alert("Hello! I am an alert box!");
});

Check here for select2 documentation

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