jQuery セレクトボックスの選択要素の値を抽出する方法
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
書式
1.セレクトボックスの項目の選択
$('select[name="name属性"]’)
例$(“select[name=’city’]")
2.changeイベントの定義
$('select[name="name属性"]’).change(function (){処理コード}
3.選択したオプションの値の取得
$(“select[name=’属性] option:selected").val();
使用例
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("select[name='city']").change(function(){ var val = $("select[name='city'] option:selected").val(); alert(val); }); }); </script> </head> <body> <select name="city"> <option value="tokyo">東京</option> <option value="oosaka">大阪</option> <option value="fukuoka">福岡</option> </select> </body> </html>
実行結果
セレクトボックス項目の「福岡」を選択すると、「fukuoka」が表示されます。