jQuery eachを使って選択されたセレクトボックス複数の要素を指定する方法
環境
jquery 3.6.3
Google Chrome 109.0.5414.120
Windows10 Home 64bit
書式
1.ボタンのイベント定義
$(“.セレクタクラス名").on(“click",function(){処理コード})
2.セレクトボックスの複数要素を選択する
$(“#セレクトボックスのID名 option:selected").each(function(index,ele){処理コード})
3.セレクトボックスの複数属性を指定する
<select id="xxx" multiple>option要素</select>
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(function(){
$(".btnSel").on("click", function() {
//コンソールに選択された要素を選択
$("#city option:selected").each(function(index,value){
alert($(value).text() + "***" + index);
});
});
});
</script>
</head>
<body>
<select id="city" multiple>
<option selected="selected">都道府県</option>
<option>東京</option>
<option>大阪</option>
<option>福岡</option>
<option>横浜</option>
</select>
<p>
<button class= "btnSel" >選択</button> </p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(function(){
$(".btnSel").on("click", function() {
//コンソールに選択された要素を選択
$("#city option:selected").each(function(index,value){
alert($(value).text() + "***" + index);
});
});
});
</script>
</head>
<body>
<select id="city" multiple>
<option selected="selected">都道府県</option>
<option>東京</option>
<option>大阪</option>
<option>福岡</option>
<option>横浜</option>
</select>
<p>
<button class= "btnSel" >選択</button> </p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(function(){ $(".btnSel").on("click", function() { //コンソールに選択された要素を選択 $("#city option:selected").each(function(index,value){ alert($(value).text() + "***" + index); }); }); }); </script> </head> <body> <select id="city" multiple> <option selected="selected">都道府県</option> <option>東京</option> <option>大阪</option> <option>福岡</option> <option>横浜</option> </select> <p> <button class= "btnSel" >選択</button> </p> </body> </html>
実行結果
「大阪」と「福岡」を選択して「選択」ボタンを押すと、
「大阪***0」と「福岡***1」が表示されます。