Juan Salvador Portugal
Juan Salvador Portugal

Reputation: 1319

Error styling Select2 for Bootstrap 4

I'm working with Bootstrap 4, and for the <select> elements i want to use Select2.

The problem is that it does not have a official Bootstrap 4 template, so i was looking and i found this project, which is awesome.

But i having one issue with is-invalid class.

When i use it, the <select> borders change to red when the page loads and then return to its normal state

I try to make a simple class to use with the same Bootstrap color like

.invalid-select2 {
  border-color: #dc3545;
}

.invalid-select2:focus {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

But the result is the same;

You can see the problem in JSFIDDLE

Someone has idea how can i deal with it?

Thanks so much!

Upvotes: 5

Views: 12361

Answers (3)

TheRealNeil
TheRealNeil

Reputation: 233

I was able to use some CSS to style a red boarder

.is-invalid + .select2-container--bootstrap .select2-selection--single {
    border: 1px solid #f44336;
}

Upvotes: 3

Jonathan Chaplin
Jonathan Chaplin

Reputation: 2482

The flikcering is because you're adding the class the the select box's class attribute so the style is applied immediately. Afterwards, select2 classes are applied which hides the select box (causing the flicker).

One way around this is to simply apply the class when the document is ready.

$(document).ready(function(){

    $('#combo').select2
  ({
    theme: 'bootstrap'
  });

  $("#combo + span").addClass("is-invalid");

});

EDIT: To fix the focus problem you're experiencing you need to over-ride a couple of classes.

.is-invalid .select2-selection,
.needs-validation ~ span > .select2-dropdown{
  border-color:red !important;
}

.is-invalid .select2-selection selects the top part of the dropdown, and the second class (.needs-validation ~ span > .select2-dropdown) selects the actual dropdown list. Note that I've added .needs-validation to the top level div once the form is validated you can simply toggle that to was-validated

https://getbootstrap.com/docs/4.0/components/forms/#validation

Here is a fiddle

Upvotes: 6

Mohcin Bounouara
Mohcin Bounouara

Reputation: 623

Did you try to add !important to css property?

Upvotes: -1

Related Questions