javascript - 重置(撤消)添加表行操作 JQUERY

标签 javascript jquery

每次单击该按钮时,将根据用户输入添加表格行。我想知道如果用户犯了错误或改变了主意,是否有任何方法可以重置(撤消)添加表行操作。提前致谢

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table#one tbody ');
    $row = $tbody.find('tr:last');
    var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
    additionalRows = new Array(numNewRows);
    for(i=0;i<numNewRows;i++)
    {
    additionalRows[i]=` <tr>
    <td>${lastRowIndex}</td>
      <td>
      <input type="text" style="width: 100px" name="vaccineid[]"></td>
      <td><input type="text" style="width:160px"name="vaccinename1[]">   				</td>
  	  </tr>`
      lastRowIndex=lastRowIndex+1;
    }
   
    $tbody.append(additionalRows.join());
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add</button>
 <button  type="reset" name="reset" >Reset</button>

<table id="one">
  <tbody>
 </tbody>
</table>

最佳答案

您可以在单击重置按钮时使用 remove() 来删除添加的行。

$('#add-row').click(function() {
  var $tbody, $row, additionalRows;
  var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);

  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('Please enter number of injection');
  } else {

    $tbody = $('table#one tbody ');
    $row = $tbody.find('tr:last');
    var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
    additionalRows = new Array(numNewRows);
    for(i=0;i<numNewRows;i++)
    {
    additionalRows[i]=` <tr>
    <td>${lastRowIndex}</td>
      <td>
      <input type="text" style="width: 100px" name="vaccineid[]"></td>
      <td><input type="text" style="width:160px"name="vaccinename1[]">   				</td>
  	  </tr>`
      lastRowIndex=lastRowIndex+1;
    }
   
    $tbody.append(additionalRows.join());
  }
});

$('[name="reset"]').click(function() {
  $('#one tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add</button>
 <button  type="reset" name="reset" >Reset</button>

<table id="one">
  <tbody>
 </tbody>
</table>

关于javascript - 重置(撤消)添加表行操作 JQUERY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071215/

相关文章:

javascript - 单击时所有元素都会更改,而不仅仅是目标元素

javascript - 动态登录格式

使用 Apps 脚本作为源数据的 Google Drive 托管页面中的 Jquery 脚本问题

javascript - 社交媒体按钮在移动浏览器中对齐方式不同,但如果需要桌面版本则正常

javascript - 正则表达式选择 div 内的所有内容

javascript - 如何在javascript或jquery中转换Youtube发布日期(ISO 8601)格式?

javascript - 在文本更改时运行 javascript

javascript - jQuery:使用基于变量值的动态对象

javascript - 如何通过填写文本字段来检查单选按钮?

javascript - Swiper.js slidesPerGroup 或 slidesPerView 不对奇怪的项目进行分组