1
1

More than 1 year has passed since last update.

セレクトボックスの選択肢や値を取得したい時

Last updated at Posted at 2023-01-20

結論

取得したセレクトボックスは一旦配列に変換しないといけない。
下記のようにセレクトボックスのelementを配列に変換してから操作する👍

// セレクトボックス要素を取得
formElem = document.getElementById(セレクトボックスのid) 

// 選択肢のvalueを配列で取得
Array.from(formElem.options).map(option => option.value)
// 選択肢の表示部分を配列で取得
Array.from(formElem.options).map(option => option.text)

なぜ変換??

formElem = document.getElementById(セレクトボックスのid) 
formElem.options
=> HTMLoptionsCollection[option,option...]

このように 取得したセレクトボックス要素.optionsで選択肢達は取得できている...が
この状態で配列の操作をしようとすると上手くいかない

formElem.optionsは、HTMLoptionsCollectionであり、配列では無いのが原因みたい...
なので、formElem.optionsを配列に変換すれば、mapとかforEachとかを使えるようになるので、変換が必須ということですね!

formElem.options.map(o => o.value) 🙅‍♂️

const options = Array.from(formElem.options)
options.map(o => o.value) 🙆‍♂️

変換にはArray.fromやスプレッド構文が使えます!
なので、こんな感じで書き換えできます

// 選択肢のvalueを配列で取得
Array.from(formElem.options).map(option => option.value)
↓
[...formElem.options].map(option => option.value)
// 選択肢の表示部分を配列で取得
Array.from(formElem.options).map(option => option.text)
↓
[...formElem.options].map(option => option.text)

個人的にはスプレッド構文の方が記述量が少しだけ減るので好きですね笑

以上!
他の方法や間違い等あればコメントお待ちしております!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1