how to get selected option text in javascript
how to get selected option text in javascript
refs
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/options
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex
https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement
others
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/item
question
solution
// e.target
temp1.options[temp1.selectedIndex].text;
// "五楼"
temp1.selectedOptions[0].text;
// "五楼"
OK
There are two solutions, as far as I know.
both that just need using vanilla javascript
1 selectedOptions
<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.selectedOptions[0].text;
log(`option desc`, desc);
});
2 options
<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);
});
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12393273.html
未经授权禁止转载,违者必究!