Style bootstrap-select "placeholder" differently
The thing is - bootstrap-select
replaces <select>
to <button>
and <option
> to <a>
.
That makes your code problematic for two reasons:
- Your trying (and probably, succeeding) to style hidden elements (as
option
andselect
are being hidden as soon as selectpicker initiates.) - You're binding to
document.ready
instead of the initialization of bootstrap select.
Use CSS to set the style of the new elements instead of the old ones:
a.placeholder, button.bs-placeholder {
font-style: italic !important;
color: #636c72;
}
HTML (Note that bs-placeholder
class is out-of-the-box for bootstrap-select when it doesn't have a value, you don't need to add it.):
<select required class="form-control selectpicker" id="medFilter" name="medFilter" title="Select Med">
<option class="placeholder" selected value="">Search Med</option>
<option value="med-1">Med 1</option>
<option value="med-2">Med 2</option>
</select>
As long as it can be archived with css, i'd ditch the document.ready
styling approach.
Plunkr: https://plnkr.co/edit/EAbTMz1WQnFWwtLsmYbZ?p=preview
$('select[name=medFilter] option:eq(1)')
use this selector and apply your css code to this and set as placeholder.
This will always select nth element (what u have passed in option:eq(1))
Hope this will work. :)
You can do all this with pure css, it will be more manageable than doing it with js. the following styles the input in italic and with a different color if the option selected is the first one.
I've given two examples, one with disabled and hidden, and another without disabled and hidden attributes.
select option {
color: #000000;
font-style: normal;
}
select:invalid, select option[value=""] {
color: red; /* Or any color you want */
font-style: italic;
}
.form-control {
margin: 20px 0px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css" />
<select required class="form-control selectpicker" id="medFilter" name="medFilter" title="Select Med">
<option selected value="">Search Med</option>
<option value="med-1">Med 1</option>
<option value="med-2">Med 2</option>
</option>
</select>
<select required class="form-control selectpicker" id="medFilter2" name="medFilter2" title="Select Med 2">
<option selected disabled hidden value="">Search Med - Another</option>
<option value="med-1">Med 1</option>
<option value="med-2">Med 2</option>
</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>