Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying bootstrap has-error styling to a select2 element

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.

like image 665
Hardist Avatar asked Feb 01 '17 19:02

Hardist


People also ask

Why select2 is not working?

Select2 does not function properly when I use it inside a Bootstrap modal. This issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal. Since by default, Select2 attaches the dropdown menu to the <body> element, it is considered "outside of the modal".

How do I turn off Select 2?

In order to enable or disable Select2, you should call . prop('disabled', true/false) on the element. Support for the old methods will be completely removed in Select2 4.1.

How do I change the height of my Select 2?

Adding the following is enough: . select2-container . select2-choice { height: 200px; } To have it apply only after an object is selected, add/modify the corresponding css on a change event or similar. This changes the height of the select2 input field, which is not what was asked for.

How do you implement select2?

Main select2 file is located at bellow folder. So include these files in the project. Alternatively you can also use bellow CDN file without downloading, just include these lines in the project. You can also manually download the select2 package from GitHub and use in your html form.


2 Answers

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/

like image 183
Christos Lytras Avatar answered Sep 19 '22 19:09

Christos Lytras


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.

like image 30
T3.0 Avatar answered Sep 19 '22 19:09

T3.0