Consider this:
<select name="month_selection"> <optgroup label="2012"> <option value="1">January</option> </optgroup> <optgroup label="2011"> <option value="1">January</option> <option value="2">February</option>
The HTML above looks like #1 when open, and #2 when closed.
How can I get the closed version to look like #3?
The purpose is to also show the selected year without repeating it in the open options (so it looks cleaner).
Advertisement
Answer
My original (marked correct) answer is too old to be of use, so here is a more up-to-date answer that may be a helpful starting point. It has some weirdness around the select box width that would need resolving according to your UI structure. Hope it is helpful.
document.querySelector('select').addEventListener("change", function(e) { var value = e.target.value var option = e.target.querySelector("option[value='" + value + "']") var group = option.parentElement var display = document.querySelector("#value") var text = option.text + " " + group.label display.innerText = text })
#wrapper { position: relative; } #value { position: absolute; pointer-events: none; width: 100%; height: 100%; display: flex; align-items: center; font-size: 0.8rem; padding-left: 0.5em; } select { color: #FFFFFF; width: 100%; } select option { color: black; }
<html> <div id="wrapper"> <div id="value">Select Dateā¦</div> <select> <optgroup label="2012"> <option value="1">January</option> <option value="2">February</option> </optgroup> <optgroup label="2013"> <option value="3">January</option> <option value="4">February</option> </optgroup> </select> </div> </html>
Old Answer (2012)
Its good to see someone making efforts to keep a good clean UI. Kudos, more people should do this. However I’d advise against approaching to problem this way. You run a risk of trying to force an element to do something it wasn’t designed to do. Even if you find a workaround, it might end up putting you into cross browser testing hell, or simply stop working on a new browser version.
I’d suggest replacing this with a JQuery or similar scriptable SELECT widget replacement such as http://filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/. This will give you all the flexibility you need to tweak the display through JavaScript.