• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Select2 Option Class is not Displaying Correctly

 
Ranch Hand
Posts: 2286
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am building a select list in an AJAX callback.
Once the list is returned I apply select2.
There is a class set to the option that sets the background color based on a filed value when the select string is build on the server.
Before the select2 is applied the lists shows the options that should be yellow as expected.
However, once the select2 is applied the background color never changes even though when I inspect the html the class is set to yellowBG.

This is part of my AJAX callback:



The first is the html select list. the second is the html with select2 applied.
The html select displays the second option with yellow background as expected.
The select2 list shows all three option with no yellow background color on the second option.

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a pretty common thing with select2. When you apply select2 to a <select>, it basically hides the original dropdown and creates its own HTML structure for the options. So, even though your original <option> tags have classes like yellowBG-inline and show the background color correctly, select2 doesn't automatically carry those styles over to its custom dropdown.

That’s why your background colors disappear once select2 kicks in.

How to fix it? Use select2’s templateResult option to control how each dropdown item is rendered. Inside that function, you can check the original option’s classes and add the same class to the new element select2 creates.

Something like this:



Since you mentioned your list comes from the server sounds like a custom .net development project, make sure those classes are set correctly on the server side too. Then this client-side trick will make sure the colors show up in the select2 dropdown.

Hope that helps! Let me know if you want me to help with the CSS or a full working example.

 
Their achilles heel is the noogie! Give them noogies tiny ad!
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic