Applying bootstrap has-error styling to a select2 element
Asked Answered
D

2

17

I've got a select2 select menu.

Stripped version for example:

<div class="form-group has-error">
    <select name="description_id" class="select2">
        <!-- <options> -->

</div>

Applying the has-error to the text-inputs will display a red border around the input. This does not work for a select2 menu. What am I missing?

I'm using bootstrap3 and the latest select2.

Drabbet answered 1/2, 2017 at 19:30 Comment(0)
S
28

The solution on the page you have posted, is for an older version of select2. For the latest version, use this CSS code here:

.has-error .select2-selection {
    border-color: rgb(185, 74, 72) !important;
}

Now with this code and using the has-error class, you can get the proper reddish error color:

<div class="form-group has-error">
 <select name="description_id" class="select2">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
  <option>Four</option>
 </select>
</div>

Select2 with has-error class

jsFiddle example: https://jsfiddle.net/k9phxgnd/1/

Sleazy answered 3/2, 2017 at 23:3 Comment(1)
That's it, thanks a lot, can award the bounty in 12 hours :-)Drabbet
B
6

With Bootstrap 3.3 and Select2 4.0.6 the error styling may be applied as follows:

css:

.has-error {border:1px solid rgb(185, 74, 72) !important;}

jquery/javascript:

$('#YourSelect2ControlID').next().find('.select2-selection').addClass('has-error');

For Select2 controls the object containing the border styling is not the <select> element, it is one of the nested <span> elements following the <select> element. That particular span contains the .select2-selection class.

Burchfield answered 9/1, 2019 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.