1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【javascript】シンプルな動的selectの生成、option(選択肢)の追加

Posted at

#やりたいこと

一次元配列からselectの選択肢を動的に作成

#中身

selectにondblclickクリックで、optionをselectに追加

See the Pen createselect by Hirofumi Sato (@hfmst) on CodePen.

#コード

index.html
<select id="test" ondblclick="create_op()"></select>
js.html
function create_op(){
  let arr = ["","","","",""];      //適当な配列用意
  let sl = document.getElementById('test'); //対象のselect取得
  
 if(sl.length<arr.length){    //selectが空の時のみ関数実行
    for(let num in arr){      //arrの要素数を0から順にnumに入れて繰り返し処理
      let op = document.createElement('option');  //optionを新しく毎回作る
      op.text = arr[num];                         //optionのテキストに配列[num番目]の値を入れる 
      sl.appendChild(op);                         //optionをselectに追加
    }
  }
}
1
1
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?