简体   繁体   中英

Placeholder option on select element with default selected

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>

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM