ついに:
LIVE DEMO
オプションラベルは完全にはサポートされていません(W3Schoolsがサポートしていると考えている場合でも:))
騙して機能させるには、最初の空白を追加します<option>
jQueryを使用して
- 選択したオプション値を取得し、
- その値をテキストおよび空白
<option>
タグの値として設定します
jQuery:
$.fn.selectLabelize = function(){
var v = $(':selected', this).val();
$('option', this).eq(0).text(v).val(v).prop('selected', true);
};
$('select').each(function(){
$(this).selectLabelize();
});
$('select').on('change', function(){
$(this).selectLabelize();
});
次のようなHTMLを考慮に入れます。
<select>
<option></option>
<optgroup label="T1">
<option value="T1a" selected>a -- Tumor is 2 cm (3/4 of an inch) or less across.</option>
<option value="T1b">b -- Tumor is 2 cm (3/4 of an inch) or less across.</option>
<option value="T1c">c -- Tumor is 2 cm (3/4 of an inch) or less across.</option>
</optgroup>
<optgroup label="T2">
<option value="T2"> Tumor is more than 2 cm but not more than 5 cm (2 inches) across.</option>
</optgroup>
<optgroup label="T3">
<option value="T3"> Tumor is more than 5 cm across.</option>
</optgroup>
</select>
純粋なJSを使用すると、次のようになります。
PURE JS - LIVE DEMO
function selectLabelize(){
var v = this.value;
this.options[0].innerHTML = v ;
this.options[0].value = v ;
this.options[0].selected = true;
}
var sel = document.getElementsByTagName('select');
var ev = document.createEvent('Event');
ev.initEvent('change', true, false);
for(var i=0; i<sel.length; i++){
sel[i].addEventListener('change', selectLabelize );
sel[i].dispatchEvent(ev);
}