【メモ】Jqueryでselectのselectedを取得

2023.10.15

例えば、ウェブサイトでプルダウンを変更した際に、値によって文字の色を変えたい時などに用います。

こんなselectを用意します。

<select id="selectColor">
<option data-color="#000" value="1">黒</option>
<option data-color="#F00" value="2">赤</option>
<option data-color="#00F" value="3">青</option>
</select>


次にJQueryで

$(document).on( 'change', '#selectColor', function(){
    $(this).css( 'color', $(this).find('option:selected').data('color') );
} );


選択しているoptionは、「option:selected」で取得できます。

  • システム開発
  • お仕事メモ
  • JavaScript
  • jQuery
  • CSS
  • HTML