JavaScript selectbox内の値を全てを取得する方法

環境
Google Chrome  115.0.5790.170(Official Build) (64 ビット)
Windows 11 Pro 64bit

構文
let 変数名 = document.getElementById( “セレクトボックスID名" ).options;
[…変数名].forEach(option => {処理コード
selectbox内の値を全てを取得するには、「HTMLCollection」で「options」を配列化して
「forEach」などでループ処理します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<select id="city">
<option selected>yokohama</option>
<option value="1">tokyo</option>
<option value="2">oosaka</option>
<option value="3">fukuoka</option>
</select>
<script>
let gg = document.getElementById( "city" ).options;
[...gg].forEach(option => {
console.log(option.label);
console.log(option.value)
});
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <select id="city"> <option selected>yokohama</option> <option value="1">tokyo</option> <option value="2">oosaka</option> <option value="3">fukuoka</option> </select> <script> let gg = document.getElementById( "city" ).options; [...gg].forEach(option => { console.log(option.label); console.log(option.value) }); </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<select id="city">
  <option selected>yokohama</option>
  <option value="1">tokyo</option>
  <option value="2">oosaka</option>
  <option value="3">fukuoka</option>
</select>


<script>

let gg = document.getElementById( "city" ).options;
[...gg].forEach(option => {
  console.log(option.label);
  console.log(option.value)
});


</script>

</body>
</html>

実行結果
yokohama
yokohama
tokyo
1
oosaka
2
fukuoka
3

JavaScript

Posted by arkgame