LoginSignup
5
0

More than 1 year has passed since last update.

JavaScript select要素で選択された値を取得する

Last updated at Posted at 2021-07-03

サンプルhtml

<body>
  <select id="select">
    <option>選択してください</option>
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
  <div id="selectValue" style="display: inline;"></div>
  <script src="main.js"></script>
</body>

方法1

イベントオブジェクトを使用して選択された値を取得します。

main.js
const select = document.getElementById('select');
select.addEventListener('change', (e) => {
  const selectValue = document.getElementById('selectValue');
  selectValue.innerHTML = e.target.value;
});

方法2

選択されているドロップダウンのテキストを取得します。

main.js
const select = document.getElementById('select');
select.addEventListener('change', () => {
  const selectValue = document.getElementById('selectValue');
  selectValue.innerHTML = select.value;
});

方法3

リストと選択されているドロップダウンのインデックスを使用して値を取得します。

main.js
const select = document.getElementById('select');
select.addEventListener('change', () => {
  const selectValue = document.getElementById('selectValue');
  selectValue.innerHTML = select.options[select.selectedIndex].innerHTML;
});

動作検証

2021-07-03_19h42_15.gif

参考記事

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0