Add class to select2 element
Asked Answered
R

8

41

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');
Rabbinical answered 22/2, 2013 at 16:40 Comment(1)
It would be really useful to know what on Earth #myBox is ?????? Is it the select object or the subsequently created select2 span elements?????Drop
M
42

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.

Monastic answered 22/2, 2013 at 16:43 Comment(4)
Your first suggestion didn't work for me. For the second one, if you have multiple selects on the page with a single class, you need to iterate through all to add to each of them the class you need. Doing $($(".myclass").select2("container")).addClass("error") won't work.Electron
Note you have to use full version: github.com/select2/select2/issues/3302Weeping
I'm getting Uncaught TypeError: Cannot read property 'apply' of undefined for the second use just for $('#myBox').select2('container')Hitandmiss
If you get Uncaught Error: No select2/compat/containerCss(…), you need to include the select2.full.js version instead of the basic oneForseti
H
41

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

Hitandmiss answered 7/9, 2016 at 13:51 Comment(2)
Thanks, your solution save my lifeUpside
If you are looking for the actual element which containerCssClass adds the classes to, it's $selection instead of $container.Buiron
K
25

According to the documentation, containerCssClass is only a constructor property. The best you're probably going to be able to do is reinitialize it when you get an error via:

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

Note from comments: If you get Uncaught Error: No select2/compat/containerCss(…), you need to include the select2.full.js version instead of the basic one

Kingofarms answered 22/2, 2013 at 16:54 Comment(4)
Thanks for suggesting to add select2.full.jsMuggy
@Kingofarms Where do I download the full version? I can't seem to find it.Partin
Nvmd, I downloaded off of Nuget which was basically legacyPartin
Best answer, need to reference the select2.full.js instead of the basic one.Leathers
B
21

For those wandering here from google, the property containerCssClass has a misleading name since it doesn't actually add any classes to the container element, but rather to the selection element. You can see this when you inspect the generated html.

I came across a nice little hack here that allows you to apply your css class to the container by adding it to the theme property, like so:

$('#my-select').select2({
    theme: "bootstrap myCssClass",
});
Bickford answered 17/10, 2018 at 18:47 Comment(1)
If you want to keep the default class and add your custom class upon it you can try somthing like: theme:"default your-custom-class"Snapback
I
6

use theme option.

 $(".select").select2({
        placeholder: "",
        allowClear: false,
        theme: "custom-option-select"
    });
Inspiration answered 13/12, 2016 at 6:43 Comment(0)
G
2

Easiest way:

Create a parent class like

<div class="select-error">
    <select id="select2" name="select2" data-required class="form-control">
        <option value="" selected>No selected</option>
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
</div>

when you validate it with jquery or php just add style or css to .select-error class like

style="border:1px solid red; border-radius: 4px"

jQuery example:

$('[data-required]').each(function() {
  if (!$(this).val()) {
    if ($(this).data('select2')) {
      $('.select-error').css({
        'border': '1px solid red',
        'border-radius': '4px'
      });
    }
  });
Genethlialogy answered 28/8, 2016 at 21:59 Comment(2)
While not answering the question exactly, I'm pretty sure this what the majority of viewers actually needMisbegotten
But what if I have 2 different selects this will also affect the second select and change it to red borderHaste
C
0

You can use dropdownCssClass opiton

$("#myBox").select2({
    containerCssClass: "error" 
});
Cryptozoic answered 28/7, 2016 at 4:10 Comment(0)
O
0

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 the span when there is no dropdown shown. this totaly worked for me.

$($(id).data('select2').$container).addClass("your-custom-class")
$($(id).data('select2').$container).click(() => $.each($("span.select2-container"), (index, value) => {
    if (index === $("span.select2-container").length - 1) {
        $(value).addClass("your-custom-class")
    }
}))
Orectic answered 15/1, 2021 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.