如何使用JavaScript删除表格中的特定行?

5

我迄今为止实现的内容:

  1. 在输入字段中输入值并单击“添加”按钮,输入的值将添加到新行。
  2. 当我单击删除按钮时,所有行都会被删除。

我需要实现的内容:

  1. 每一行应添加复选框。
  2. 如果我选中复选框并单击“删除”按钮,则只应删除该特定行,并且如果我选择多个复选框,则也应起作用。 3.单击添加按钮后清除输入字段。 有谁可以检查一下并告诉我如何做到这一点。

//Javascript code to Add new rows onclick of a button and to delete row .
function addMoreRows() {

    var user = document.getElementById('user_id').value;
    var date = document.getElementById('date').value;
    var color = document.getElementById('color').value;
    var table = document.getElementById('tbl_id');

    var row = table.insertRow();

    var userName = row.insertCell(0);
    var Date = row.insertCell(1);
    var Color = row.insertCell(2);
    var checkbox = row.insertCell(3);

    userName.innerHTML = user;
    Date.innerHTML = date;
    Color.innerHTML = color;

}

function deleteMoreRows(tableID) {

    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    for (var i = 0; i < rowCount; i++) {

        table.deleteRow(i);
        rowCount--;
        i--;
    }
}
<!-- HTML markup for the input fields and table . -->
<form align="center" method="GET">
   Enter your name : <input type="text" name="users" id="user_id"  value="name" onfocus="if(this.value == 'name') {this.value=''}" onblur="if(this.value == ''){this.value ='name'}"><br>
   Select the Date : <input type="date"  id="date"><br>
   Select your favorite color: 
   <select id="color" required>
      <option value="yellow">yellow</option>
      <option value="red">red</option>
   </select>
   <br>
   <br>
   <input type="button" id="mysubmit" value="Add Row" onClick="addMoreRows()">
   <input type="button" id="delete" value="Delete" onClick="deleteMoreRows('tbl_id')">
</form>
<br>
<br>
<table id="tbl_id" style="text-align:center" align="center" valign="top">
   <thead>
      <tr>
         <th style="width:200px;">Name</th>
         <th style="width:200px;">Date</th>
         <th style="width:200px;">Color</th>
      </tr>
   </thead>


你在尝试实现剩余逻辑时遇到了任何问题吗? - palaѕн
按下 F12 打开 JavaScript 控制台。当您点击删除时,会出现哪些错误? - Matt
@mkaatman,我没有收到任何错误信息,但是当我点击删除时它会删除所有行,我需要在选择复选框时删除特定的行。但我不确定如何为每一行添加复选框并进行验证。 - Vivek
为什么你不在这里使用jQuery? - Majid Nayyeri
你需要将checkbox.innerHTML设置为包含复选框并与行相关联的唯一id的输入字段。 - Matt
1个回答

5
请问这个对您是否可行:

//Javascript code to Add new rows onclick of a button and to delete row .

var rowId = 0;

function addMoreRows() {

    var user = document.getElementById('user_id').value;
    var date = document.getElementById('date').value;
    var color = document.getElementById('color').value;
    var table = document.getElementById('tbl_id');

    var row = table.insertRow();

    var rowBox = row.insertCell(0);
    var userName = row.insertCell(1);
    var Date = row.insertCell(2);
    var Color = row.insertCell(3);
    var checkbox = row.insertCell(4);

    rowBox.innerHTML = '<input type="checkbox" id="delete' + getRowId() + '">';
    userName.innerHTML = user;
    Date.innerHTML = date;
    Color.innerHTML = color;

}

function deleteMoreRows(tableID) {

    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var selectedRows = getCheckedBoxes();

    selectedRows.forEach(function(currentValue) {
      deleteRowByCheckboxId(currentValue.id);
    });
}

function getRowId() {
  rowId += 1;
  return rowId;
}

function getRowIdsFromElements($array) {
  var arrIds = [];

  $array.forEach(function(currentValue, index, array){
    arrIds.push(getRowIdFromElement(currentValue));
  });

  return arrIds;
}

function getRowIdFromElement($el) {
    return $el.id.split('delete')[1];
}

//ref: https://dev59.com/vGoy5IYBdhLWcg3wa9bf
function getCheckedBoxes() {
  var inputs = document.getElementsByTagName("input");
  var checkboxesChecked = [];

  // loop over them all
  for (var i=0; i < inputs.length; i++) {
     // And stick the checked ones onto an array...
     if (inputs[i].checked) {
        checkboxesChecked.push(inputs[i]);
     }
  }

  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

//ref: https://dev59.com/q2445IYBdhLWcg3wO31u
function deleteRowByCheckboxId(CheckboxId) {
    var checkbox = document.getElementById(CheckboxId);
    var row = checkbox.parentNode.parentNode;                //box, cell, row, table
    var table = row.parentNode;

    while ( table && table.tagName != 'TABLE' )
        table = table.parentNode;
    if (!table) return;
    table.deleteRow(row.rowIndex);
}
<!-- HTML markup for the input fields and table . -->
<form align="center" method="GET">
   Enter your name : <input type="text" name="users" id="user_id"  value="name" onfocus="if(this.value == 'name') {this.value=''}" onblur="if(this.value == ''){this.value ='name'}"><br>
   Select the Date : <input type="date"  id="date"><br>
   Select your favorite color: 
   <select id="color" required>
      <option value="yellow">yellow</option>
      <option value="red">red</option>
   </select>
   <br>
   <br>
   <input type="button" id="mysubmit" value="Add Row" onClick="addMoreRows()">
   <input type="button" id="delete" value="Delete" onClick="deleteMoreRows('tbl_id')">
</form>
<br>
<br>
<table id="tbl_id" style="text-align:center" align="center" valign="top">
   <thead>
      <tr>
         <th style="width:200px;">Delete</th>
         <th style="width:200px;">Name</th>
         <th style="width:200px;">Date</th>
         <th style="width:200px;">Color</th>
      </tr>
   </thead>


非常感谢您的帮助!!这正是我所寻找的。它完美地运行。再次感谢。 - Vivek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接