JavaScript プロパティ「options」を使用してセレクトボックス(selectbox)内の値を全てを取得する

環境
Google Chrome 111.0.5563.147
Windows 10 Home 64bit

書式
1. セレクトボックスの要素を取得します
let 変数名 =document.getElementById( “セレクトボックスのID名" ).options;

2.forEachでoptionsをループ処理します
[…変数名].forEach(option=>{処理コード}
ラベルの値の取得
option.label
selectboxの値の取得
option.value

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<select id="city">
<option selected>都市の選択</option>
<option value="101">Tokyo</option>
<option value="202">Oosaka</option>
<option value="303">Fukuoka</option>
</select>
<p>
<button onclick="funA()">表示</button></p>
<script>
function funA() {
let cft = document.getElementById( "city" ).options;
[...cft].forEach(option => {
console.log(option.label)
console.log(option.value)
});
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <select id="city"> <option selected>都市の選択</option> <option value="101">Tokyo</option> <option value="202">Oosaka</option> <option value="303">Fukuoka</option> </select> <p> <button onclick="funA()">表示</button></p> <script> function funA() { let cft = document.getElementById( "city" ).options; [...cft].forEach(option => { console.log(option.label) console.log(option.value) }); } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<select id="city">
  <option selected>都市の選択</option>
  <option value="101">Tokyo</option>
  <option value="202">Oosaka</option>
  <option value="303">Fukuoka</option>
</select>
<p>
<button onclick="funA()">表示</button></p>

<script>
function funA() {
let cft = document.getElementById( "city" ).options;

[...cft].forEach(option => {
  console.log(option.label)
  console.log(option.value)
});
}
</script>

</body>
</html>

実行結果
都市の選択
都市の選択
Tokyo
101
Oosaka
202
Fukuoka
303

JavaScript

Posted by arkgame