「jQuery」セレクトボックスの選択文字を取得するサンプル

環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.6
jQuery 3.6.0

構文
$(“.city option:selected").text();
classセレクタ(.city)で対象を特定します。
option:selectedで選択した文字を取得しています。

使用例

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>
<script>
$(function(){
$("#btnchk").click(function() {
// 選択した文字を取得します
const strVal = $(".city option:selected").text();
$("#show").text(strVal);
});
});
</script>
</head>
<body>
<p>選択した都市名: <span id="show"></span></p>
<select class="city">
<option value="tokyo">東京</option>
<option value="oosaka">大阪</option>
<option value="fukuoka">福岡</option>
</select>
<p>
<input type="button" id="btnchk" 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(){ $("#btnchk").click(function() { // 選択した文字を取得します const strVal = $(".city option:selected").text(); $("#show").text(strVal); }); }); </script> </head> <body> <p>選択した都市名: <span id="show"></span></p> <select class="city"> <option value="tokyo">東京</option> <option value="oosaka">大阪</option> <option value="fukuoka">福岡</option> </select> <p> <input type="button" id="btnchk" 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(){
      $("#btnchk").click(function() {
            // 選択した文字を取得します
            const strVal = $(".city option:selected").text();
            $("#show").text(strVal);
      });
});
</script>
</head>
<body>
<p>選択した都市名: <span id="show"></span></p>

<select class="city">
    <option value="tokyo">東京</option>
    <option value="oosaka">大阪</option>
    <option value="fukuoka">福岡</option>
</select>
<p>
<input type="button" id="btnchk" value="検証" />
</p>

</body>
</html>

実行結果
「大阪」を選択し「検証」ボタンを押すと、「選択した都市名: 大阪」が表示されます。

jQuery

Posted by arkgame