I have successfully managed to apply a different style to my normal select elements if the selected option is the first one (the placeholder) with jQuery like so :
<script type="text/javascript">
$(document).ready
(
function ()
{
$('select').each(function (index, value)
{
if($(this).val()==="")
{
$(this).css('font-style', 'italic');
$(this).css('color', '#636c72');
$(this).children().css('font-style', 'normal');
}
else
{
$(this).css('font-style', 'normal');
$(this).css('color', 'black');
$(this).children().css('font-style', 'normal');
}
});
}
);
</script>
However, some of my forms are using the bootstrap-select component due to the sheer amount of entries they contain (can be thousands) and the necessity of having a way to narrow down the entries with text searches. Those components produce MUCH more complicated HTML and the above code does not work at all.
I am trying to find a way to apply the same logic as with my normal selects : style the input in italic and with a different color if the option selected is the first one. Here is an example of such select :
<select class="form-control selectpicker" id="medFilter" name="medFilter" th:value="${medFilter}"
onchange="this.form.submit()" data-live-search="true" title="Select Med">
<option value="">Search Med</option>
<option th:each="med : ${meds}" th:value="${med.id}"
th:text="${med.toString()}" th:selected="${med.id == medFilter}">
</option>
</select>
Has anyone ever been able to achieve this?
The thing is - bootstrap-select
replaces <select>
to <button>
and <option
> to <a>
.
That makes your code problematic for two reasons:
option
and select
are being hidden as soon as selectpicker initiates.)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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With