LoginSignup
4
2

More than 5 years have passed since last update.

selectタグで選択されたoptionのカスタム属性を取得する方法

Last updated at Posted at 2018-07-10

プルダウンから選択された属性(カスタムデータ属性)をinnerHTMLへ出力するサンプル

jQueryでのやり方はたくさんあるけど、プレーンなjsではサンプルがなかったので。

select.js

<table border="1">
<tr>
  <td>hoge区分</td>
  <td>
  <select id="sel" 
       onchange="document.getElementById('text1').textContent = this.options[this.selectedIndex].dataset.view">
    <option data-view=""></option>
    <option data-view="aaa" value="1">1 AAA</option>
    <option data-view="bbb" value="2">2 BBB</option>
    <option data-view="ccc" value="3">3 CCC</option>
    </select>
  </td>
  <td id="text1" >hogehoge</td>
</tr>
</table>

単純にvalue値を取得するケース。
onchangeイベントを以下の記述に変更。

basic.js
document.getElementById('text1').value = this.value;

4
2
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
4
2