0
0

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.

セレクトボックスで選んだ数だけ要素を追加する

Last updated at Posted at 2021-04-17

セレクトボックスで数字を選び、選んだ数字の数だけ要素を追加する方法。
liタグの数を変える。

html
<select name='addNumber'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>

<ul id="addTarget">
  <li>最初の要素</li>
</ul>
jquery
$('[name=addNumber]').on('change', function(){
  //追加要素をいったん全部消す
  $(".addContent").remove()
  //セレクトボックスから数字を取ってくる
  let num = $('[name=addNumber]').val()
  //セレクトボックスの文字を数字にする
  num = Number(num)
  //追加するコンテンツ
  let add_content = '<li class="addContent">追加</li>'
  //要素数が2個以上は追加
  if(num > 1){
    for (let i=1; i<num; i++) {
      $('#addTarget').append(add_content)
    }
  }
});
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?