我有一个这样的下拉列表:
<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
我如何才能获得实际的选项文本,而不是使用JavaScript的值?我可以通过如下方式获取值:
<select id="box1" onChange="myNewFunction(this.selectedIndex);" >
但我想要猫而不是7122。
据我所知,有两种解决办法。
两者都只需要使用普通的javascript
1 selectedOptions
现场演示
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.selectedOptions[0].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
两个选择
现场演示
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.options[select.selectedIndex].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>