peledies peledies - 4 months ago 145
jQuery Question

add class to select2 element

the documentation is either terrible or im missing something. Im trying to add an error class to a select2 box for form validation. Its just a 1px red border.

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

I have tried the following with no luck:

$("#myBox").select2().containerCssClass('error');


thanks for looking.

Answer

jQuery uses JSON objects to initalize, so I gues this one will aswell:\

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

If you wan't 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.

Comments