Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to select2 element

The documentation is either terrible or I'm missing something. I'm trying to add an error class to a select2 box for form validation. It's just a 1px red border.

I found the containerCssClass method in the documentation, but I'm not sure how to apply it.

I have tried the following with no luck:

$("#myBox").select2().containerCssClass('error'); 
like image 688
Deac Karns Avatar asked Feb 22 '13 16:02

Deac Karns


People also ask

How do I add a class to a select2-container?

select2 would make an other span with select2-container class right at the end of the body every time you click on the span tag and the dropdown with the options become visible, so you can use your click event and trigger a function that add your custom class to the dropdown container at the end of the body and also ...


2 Answers

jQuery uses JSON objects to initialize, so I guess this one will as well:\

$("#myBox").select2({ containerCssClass : "error" }); 

If you want to add/remove a class you can do this after you initialized it

$($("#myBox").select2("container")).addClass("error"); $($("#myBox").select2("container")).removeClass("error"); 

The above function gets the DOM node of the main container of select2 e.g.: $("#myBox").select2("container")

Important
You will need to use the container method to get the container since you won't edit the SELECT directly but select2 will generate other HTML to simulate a SELECT which is stylable.

like image 66
Niels Avatar answered Oct 11 '22 05:10

Niels


For already initialized select2 element I have tried @Niels solution but it resulted in an error: Uncaught TypeError: Cannot read property 'apply' of undefined

Went into the source and this has been working instead:

$('#myBox').data('select2').$container.addClass('error') $('#myBox').data('select2').$container.removeClass('error') 

Using select2 v4.0.3 full

like image 29
Jared Avatar answered Oct 11 '22 04:10

Jared