xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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);
});




posted @ 2020-03-02 01:11  xgqfrms  阅读(186)  评论(4编辑  收藏  举报