12
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

jQueryフォーム追加削除

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

// 追加
$('#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.

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
Sign upLogin
12
Help us understand the problem. What are the problem?