Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

jQueryフォーム追加削除

More than 1 year has passed since last update.

思った以上に使う機会があるのでメモ

// 追加
$('#demo-plus').on('click', function(){
  var inputCount = $('#demo-area .unit').length;
  if (inputCount < maxCount){
    var element = $('#demo-area .unit:last-child').clone(true);// 末尾をイベントごと複製
    // 複製したinputのクリア
    var inputList = element[0].querySelectorAll('input[type="text"], textarea');
    for (var i = 0; i < inputList.length; i++) {
      inputList[i].value = "";
    }
    $('#demo-area .unit').parent().append(element);// 末尾追加
  }
});
// 削除
$('.demo-minus').on('click', function(){// イベントごと複製しているのでonのselectorは未設定
  var inputCount = $('#demo-area .unit').length;
  if (inputCount > minCount){
    $(this).closest('.unit').remove();
  }
});

構造

.unitが複製単位

#demo-area
  .unit
    .demo-minus
  .unit
    .demo-minus

#demo-plus

See the Pen RmXqmJ by horikeso (@horikeso) on CodePen.

horikeso
個人的な備忘録ばかりですが、よろしくお願いします。難しいことはよくわかりません!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away