「jQuery」セレクトボックスのchangeイベントのサンプル

環境
jquery3.6.0
Google Chrome 100.0.4896.127

書式
<select id ="セレクタID名">
$(“#セレクタID名").change(function() {
処理コード
}
changeメソッドを使って、セレクトボックスの値が変化したらvalue値を取得します。
使用例

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.0/jquery.min.js"></script>
<select id="city">
<option value="tokyo">東京</option>
<option value="oosaka">大阪</option>
<option value="fukuoka">福岡</option>
</select>
<script>
//セレクトボックスIDセレクタcityのchangeイベント
$("#city").change(function() {
// 選択されたvalue値を取得
const res = $("#city").val();
$("#show").text(res);
});
</script>
</head>
<body>
<p>選択した都市: <span id="show"></span></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <select id="city"> <option value="tokyo">東京</option> <option value="oosaka">大阪</option> <option value="fukuoka">福岡</option> </select> <script> //セレクトボックスIDセレクタcityのchangeイベント $("#city").change(function() { // 選択されたvalue値を取得 const res = $("#city").val(); $("#show").text(res); }); </script> </head> <body> <p>選択した都市: <span id="show"></span></p> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="city">
    <option value="tokyo">東京</option>
    <option value="oosaka">大阪</option>
    <option value="fukuoka">福岡</option>
</select>
<script>
  //セレクトボックスIDセレクタcityのchangeイベント
      $("#city").change(function() {
            // 選択されたvalue値を取得
            const res = $("#city").val();
            $("#show").text(res);
      });

</script>
</head>
<body>
<p>選択した都市: <span id="show"></span></p>
</body>
</html>

実行結果
「大阪」を選択すると、「選択した都市: oosaka」が表示されます

jQuery

Posted by arkgame