Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jquery - 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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...