jQuery セレクトボックスの選択した文字を取得するサンプル
構文
jquery 3.6.0
Google Chrome 106.0.5249.121
構文
1.セレクトボックスの選択した文字を取得
IDセレクタで対象を特定し、option:selectedで選択した文字を取得します
const 変数名 = $(“#セレクターID名 option:selected").text();
2.ボタンのクリックイベント
$(“#ボタンのIDセレクター名").click(function(){処理コード}
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#btnshow").click(function() {
// 選択した文字を取得
const result = $("#city option:selected").text();
$("#show").text(result);
});
});
</script>
</head>
<body>
<p>都市: <span id="show"></span></p>
<select id="city">
<option value="tokyo">東京</option>
<option value="oosaka">大阪</option>
<option value="fukuoka">福岡</option>
</select>
<p><input type="button" id="btnshow" value="表示" /></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#btnshow").click(function() {
// 選択した文字を取得
const result = $("#city option:selected").text();
$("#show").text(result);
});
});
</script>
</head>
<body>
<p>都市: <span id="show"></span></p>
<select id="city">
<option value="tokyo">東京</option>
<option value="oosaka">大阪</option>
<option value="fukuoka">福岡</option>
</select>
<p><input type="button" id="btnshow" value="表示" /></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $("#btnshow").click(function() { // 選択した文字を取得 const result = $("#city option:selected").text(); $("#show").text(result); }); }); </script> </head> <body> <p>都市: <span id="show"></span></p> <select id="city"> <option value="tokyo">東京</option> <option value="oosaka">大阪</option> <option value="fukuoka">福岡</option> </select> <p><input type="button" id="btnshow" value="表示" /></p> </body> </html>
結果
セレクトボックスの「福岡」を選択して、「表示」ボタンを押すと、「都市: 福岡」が表示されます。