jQuery selectボックスにchange()イベントを使うサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

構文
1.selectボックスのchangeイベントの定義
$('select’).change(function(){処理コード})
2.selectボックスに選択した項目のテキストを抽出します
$('option:selected’).text()

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!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').change(function() {
var ele = $('option:selected').text();
alert(ele);
});
});
</script>
</head>
<body>
<select>
<option>東京</option>
<option>大阪</option>
<option>横浜</option>
</select>
</body>
</html>
<!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').change(function() { var ele = $('option:selected').text(); alert(ele); }); }); </script> </head> <body> <select> <option>東京</option> <option>大阪</option> <option>横浜</option> </select> </body> </html>
<!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').change(function() {
       var ele = $('option:selected').text();
       alert(ele);
    });
});
</script>
</head>
<body>

<select>
    <option>東京</option>
    <option>大阪</option>
    <option>横浜</option>
</select>

</body>
</html>

実行結果
「大阪」を選択すると、コンソールログに文字列「大阪」が出力されます。

jQuery

Posted by arkgame