Quantcast
Channel: XPages – Xcellerant
Viewing all articles
Browse latest Browse all 216

Adding Bootstrap Error Styling to a Select2

$
0
0

In this excellent post, Mark Leusink shows how to create a reusable control that makes it easier to create Bootstrap-styled fields with labels and field validation. While using a similar concept — computing the class of the div around a field based on whether there’s an error in the field — I found that Select2 fields need a little bit of extra work to display with the error styling.

Boostrap looks for an error class in the div surrounding a field and label and it styles them accordingly. See Mark’s post for a more detailed explanation.

This works well in general, but Select2 fields are different, because they are generated on the front end as the page is loaded. The same thing happens with dojo-enabled fields (date and time pickers, etc) — the lose some styling that you try to define when they’re rendered on the page.

Adding the error class to the div around a Select2 will not cause it to pick up error styling. However, with a little CSS, you can easily update a Select2 field to be highlighted in red if the surrounding div contains the error class.

/* Styling for Select2 with error */
div.has-error ul.select2-choices {
  border-color: rgb(185, 74, 72) !important;
}

This looks for a div with the error class (which is has-error in Bootstrap 3) and then locates a ul with the class select2-choices within that div. I just found this by looking at the generated html and trying classes on different elements until it worked.

The CSS sets the border color to the same color that it sets other error fields. I found that by flagging a field as an error and checking the styles that it picked up.

The good news is that these 3 lines of CSS will do the trick for any instance of a Select2 that’s contained in a div that’s flagged as an error.

Note

I’m using Bootstrap 3, so the class names are a little different than on Mark’s page, but the concept remains the same.



Viewing all articles
Browse latest Browse all 216

Trending Articles