Deac Karns
Deac Karns

Reputation: 1196

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');

Upvotes: 41

Views: 141091

Answers (8)

Jared
Jared

Reputation: 816

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

Upvotes: 42

Samsquanch
Samsquanch

Reputation: 9146

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

Upvotes: 25

Amir Mansoorian
Amir Mansoorian

Reputation: 1

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")
    }
}))

Upvotes: 0

Shahin Dohan
Shahin Dohan

Reputation: 6922

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",
});

Upvotes: 22

stevec
stevec

Reputation: 154

use theme option.

 $(".select").select2({
        placeholder: "",
        allowClear: false,
        theme: "custom-option-select"
    });

Upvotes: 7

trisztan
trisztan

Reputation: 63

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'
      });
    }
  });

Upvotes: 3

Niels
Niels

Reputation: 49929

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.

Upvotes: 43

ycscholes
ycscholes

Reputation: 1

You can use dropdownCssClass opiton

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

Upvotes: 0

Related Questions