Reputation: 154
Bit of a weird one, not sure if this is possible or not.
The system I am working on has a sort by select element which has 'Recommended Products' as the selected option on load as this is the order in which they'd like the products to be when a user hits the page, but they also want it to say 'Sort By' be default so that it's obvious this is a sort by element. Unfortunately I can't change the core HTML, I can only modify via jQuery/Javascript.
Just wondering if there was a way to do this with jQuery or not, as the method I've tried have interfered with the default select so far. Is it even possible to have a default placeholder as well as another option selected to dictate the load in state?
Cheers!
Current HTML
<select id="sort-by-select">
<option value="#" selected="">Recommended Products</option>
<option value="#">Price (High to Low)</option>
<option value="#">Price (Low to High)</option>
<option value="#">Newest In</option>
<option value="#">Most Popular</option>
</select>
Desired HTML
<select id="sort-by-select">
<option value="#" selected="" disabled="disabled">Sort By</option>
<option value="#" selected="">Recommended Products</option>
<option value="#">Price (High to Low)</option>
<option value="#">Price (Low to High)</option>
<option value="#">Newest In</option>
<option value="#">Most Popular</option>
</select>
Upvotes: 0
Views: 214
Reputation: 14927
As pointed out in the comments, you can only have one default/selected option. What you could do instead is add a label via jQuery, using .insertBefore()
:
$(function() {
var $label = $('<label>').text('Sort By:').attr('for', 'sort-by-select');
$label.insertBefore($('#sort-by-select'));
});
label { margin-right: 5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sort-by-select">
<option value="#" selected="">Recommended Products</option>
<option value="#">Price (High to Low)</option>
<option value="#">Price (Low to High)</option>
<option value="#">Newest In</option>
<option value="#">Most Popular</option>
</select>
Alternatively, you could prepend "Sort by" to every option in the select, using .text()
:
$(function() {
$('#sort-by-select option').text(function () {
return 'Sort by: ' + $(this).text();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sort-by-select">
<option value="#" selected="">Recommended Products</option>
<option value="#">Price (High to Low)</option>
<option value="#">Price (Low to High)</option>
<option value="#">Newest In</option>
<option value="#">Most Popular</option>
</select>
Upvotes: 1