简体   繁体   中英

How can I add a class to the selected element on click event with select2?

We are using Select2 version 4.0.0-rc2

To improve mobile usage we would like to implement adding a class to the clicked item in the drop down.

I tried reacting to the select2 events like this:

  element.select2({}).on('select2:open', function(){
     this.addClass('my-class');
  }

However, the problem with this is that 'this' is the option and not the rendered select li. I believe 'this' is because Select2 delegates/passes the event down to the select option.

I also tried directly targeting the result item like this:

$('.select2-results li ["aria-selected=true"]').on('click', function(){
    this.addClass('my-class');
}

But I get the same problem as above. 'This' and even Event.target are option.

I found some suggestions from older versions of select2 and tried this:

  element.select2({}).on('select2:open', function(e){
     $('.search-results li [aria-selected=true]').on('mouseup', function(e){
     e.stopPropagation();
     this.addClass('my-class');
  }

This one only seemed to work on the second click. So, I clicked to open the list, I select an item, nothing happens, I select another item, it then gets the class.

  • Note: Some of the selectors above may not be accurate but its just to give an example. All of my code worked except that I couldnt get my event to fire on the right element.

Could anyone suggest a fix?

Alternatively, on the Select2 page ( https://select2.github.io/options.html ) , they suggest that in version 4 you can write plugins using an adapter. Im not familiar with adapters and can only assume they mean the adapter pattern? I dont understand how I would even start with this. I understand the concept, I write a wrapper so that my functions are called and I can modify them and also pass through to the library methods? If anyone could provide any further info on how I could do that, it would be greatly appreciated.

I do not know how to add a specific class to selected ìtems but you can use the [aria-selected=true] CSS selector to customize their style.

.select2-container--default .select2-results__option[aria-selected=true] {
    color: red;
    font-weight: bold;
}

For our case where we wanted to adjust it for mobile touch, we managed to get it working with this code. Note the 'tap' event is provided by jQuery mobile:

element.select2({}).on('select2:open', function(e){
 $('.search2-results li').on('tap', function(e){
     $(e.target).addClass('my-class');
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM