Javascript 使用 jQuery 动态添加行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2145012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:56:40  来源:igfitidea点击:

Adding rows dynamically with jQuery

javascriptjqueryhtmlforms

提问by Alix Axel

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

我正在构建一个需要多个可选输入的表单,我所拥有的基本上是这样的:

form example

form example

Every time a user presses the plus button a new row of form inputs should be added to the form, how can I do this in jQuery? Also, is it possible to automatically add a new row when all rows(or just the last row, if it's easier / faster) are filled?That way the user wouldn't need to press the plus button.

每次用户按下加号按钮时,都应将新的表单输入行添加到表单中,我如何在 jQuery 中执行此操作?另外,是否可以在填充所有行(或仅最后一行,如果更容易/更快)时自动添加新行这样用户就不需要按下加号按钮。

I'm sorry for asking maybe such a basic question but I'm still very green with jQuery, I could do this with PHP but I'm sure Javascript / jQuery plays a more appropriate role here.

我很抱歉问了这样一个基本问题,但我对 jQuery 仍然很陌生,我可以用 PHP 做到这一点,但我确信 Javascript / jQuery 在这里扮演更合适的角色。

Thanks in advance!

提前致谢!



@alex:

@亚历克斯:

<!DOCTYPE html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$form = $('#personas');
$rows = $form.find('.person');

$('a#add').click(function() {
    $rows.find(':first').clone().insertAfter($rows.find(':last'));
    $justInserted = $rows.find(':last');
    $justInserted.hide();
    $justInserted.find('input').val(''); // it may copy values from first one
    $justInserted.slideDown(500);
});
</script>
</head>

<body>
<form id="personas" name="personas" method="post" action="">
  <table width="300" border="1" cellspacing="0" cellpadding="2">
    <tr>
      <td>Name</td>
      <td>More?</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name[]" id="name[]" /></td>
      <td><a href="#" id="add">+</a></td>
    </tr>
  </table>
</form>
</body>
</html>

采纳答案by Rippo

This will get you close, the add button has been removed out of the table so you might want to consider this...

这将使您关闭,添加按钮已从表格中删除,因此您可能需要考虑此...

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    });
</script>

HTML markup looks like this

HTML 标记如下所示

  <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>
  </table>

EDITTo empty a value of a textbox after insert..

编辑插入后清空文本框的值..

    $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
    $('#mytable tbody>tr:last #name').val('');
    return false;

EDIT2Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this

EDIT2无法自拔,要重置插入的 TR 中的所有下拉列表,您可以执行此操作

$("#mytable tbody>tr:last").each(function() {this.reset();});           

I will leave the rest to you!

剩下的交给你!

回答by javagirl

As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):

作为上述答案的补充:您可能需要更改输入元素的名称/ID 中的 ID(请注意,字段名称中不应包含数字):

<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>

I have done this having some global variable by default set to 0:

我已经这样做了,默认情况下将一些全局变量设置为 0:

var globalNewIndex = 0;

and in the add function after you've cloned and resetted the values in the new row:

在克隆并重置新行中的值后,在 add 函数中:

                var newIndex = globalNewIndex+1;
                var changeIds = function(i, val) {
                    return val.replace(globalNewIndex,newIndex);
                }
                $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
                globalNewIndex++;

回答by iJay

I have Tried something like this and its works fine;

我已经尝试过这样的事情并且效果很好;

enter image description here

enter image description here

this is the html part :

这是 html 部分:

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

这是 Javascript 部分;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

最后 PHP 提交部分:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

您可以通过动态表格行插入器找到更多详细信息

回答by alex

Untested. Modify to suit:

未经测试。修改以适应:

$form = $('#my-form');

$rows = $form.find('.person-input-row');

$('button#add-new').click(function() {

    $rows.find(':first').clone().insertAfter($rows.find(':last'));

    $justInserted = $rows.find(':last');
    $justInserted.hide();
    $justInserted.find('input').val(''); // it may copy values from first one
    $justInserted.slideDown(500);


});

This is better than copying innerHTML because you will lose all attached events etc.

这比复制 innerHTML 更好,因为您将丢失所有附加事件等。

回答by Drew Taylor

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.

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);
});