Adding rows dynamically with jQuery

前端 未结 5 1008
天命终不由人
天命终不由人 2020-11-28 02:48

I\'m building a form where I need multiple optional inputs, what I have is basically this:

Every time a user presses the plus button a new row of form inputs

5条回答
  •  孤街浪徒
    2020-11-28 03:14

    Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.

    $('.js-addNew').on('click', function(e) {
       e.preventDefault();
       var $rows   = $('.person'),
           $last   = $rows.filter(':last'),
           $newRow = $last.clone().insertAfter($last);
    
       $last.find($('.js-addNew')).remove(); // remove old button
       $newRow.hide().find('input').val('');
       $newRow.slideDown(500);
    });
    

提交回复
热议问题