最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - update id name on html table elements when delete middle rows - Stack Overflow

programmeradmin3浏览0评论

The function addRow will add row in the last child of a table, and deleteRow will delete checked row. The problem is, when I delete middle row, i.e. row 2 from 3 rows available, then the row 3 element's id still not updated even though there is only 2 rows remaining. How to update the row 3's id value?

function addRow() {
  var tblList = document.getElementById("table1");
  var tblBody = tblList.tBodies[0];

  const lastRow = document.querySelector('#table1 tr:last-child td:first-child+td input') || 0;
  const length = tblBody.rows.length;

  try {
    var row = tblBody.insertRow(length);
  } catch (e) {
    console.log(e);
    return false;
  }

  var newCell0 = row.insertCell(0);
  newCell0.innerHTML = `
        <table style="width: 100%;">
            <tr>
                <td>
                    <input type="checkbox" id="eval_cb0_${length}" name="eval_cb0_${length}" value="checked" >
                </td>
                <td>
                    <label for="eval_cb0_${length}">EVAL 1</label>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" id="eval_cb1_${length}" name="eval_cb1_${length}" value="checked" >
                </td>
                <td>
                    <label for="eval_cb1_${length}">EVAL 2</label>
                </td>
            </tr>
        </table>
        `;

  var newCell1 = row.insertCell(1);
  newCell1.innerHTML = `
            <input class="row-cb" type="checkbox" name="cb_clone[]">
        `;
}



function deleteRow() {
  const checkboxes = document.querySelectorAll(".row-cb");

  const userConfirm = confirm("Are u sure?");
  if (!userConfirm) return;

  checkboxes.forEach((checkbox) => {
    if (checkbox.checked) {
      const row = checkbox.closest('tr');
      row.remove();
    }
  });
}
<table id="table1">
  <thead>
    <tr>
      <th>EVALUATION</th>
      <th></th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>
<input id="button_delete" type="button" onclick="deleteRow()" value="DELETE">
<input id="button_add" type="button" onclick="addRow()" value="ADD">

The function addRow will add row in the last child of a table, and deleteRow will delete checked row. The problem is, when I delete middle row, i.e. row 2 from 3 rows available, then the row 3 element's id still not updated even though there is only 2 rows remaining. How to update the row 3's id value?

function addRow() {
  var tblList = document.getElementById("table1");
  var tblBody = tblList.tBodies[0];

  const lastRow = document.querySelector('#table1 tr:last-child td:first-child+td input') || 0;
  const length = tblBody.rows.length;

  try {
    var row = tblBody.insertRow(length);
  } catch (e) {
    console.log(e);
    return false;
  }

  var newCell0 = row.insertCell(0);
  newCell0.innerHTML = `
        <table style="width: 100%;">
            <tr>
                <td>
                    <input type="checkbox" id="eval_cb0_${length}" name="eval_cb0_${length}" value="checked" >
                </td>
                <td>
                    <label for="eval_cb0_${length}">EVAL 1</label>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" id="eval_cb1_${length}" name="eval_cb1_${length}" value="checked" >
                </td>
                <td>
                    <label for="eval_cb1_${length}">EVAL 2</label>
                </td>
            </tr>
        </table>
        `;

  var newCell1 = row.insertCell(1);
  newCell1.innerHTML = `
            <input class="row-cb" type="checkbox" name="cb_clone[]">
        `;
}



function deleteRow() {
  const checkboxes = document.querySelectorAll(".row-cb");

  const userConfirm = confirm("Are u sure?");
  if (!userConfirm) return;

  checkboxes.forEach((checkbox) => {
    if (checkbox.checked) {
      const row = checkbox.closest('tr');
      row.remove();
    }
  });
}
<table id="table1">
  <thead>
    <tr>
      <th>EVALUATION</th>
      <th></th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>
<input id="button_delete" type="button" onclick="deleteRow()" value="DELETE">
<input id="button_add" type="button" onclick="addRow()" value="ADD">

Share Improve this question edited Mar 17 at 17:08 isherwood 61.2k16 gold badges121 silver badges170 bronze badges asked Mar 17 at 16:53 purple hippopurple hippo 594 bronze badges 8
  • 3 What do you mean by “id name”, exactly? I hope you are not going to modify the id property of an element... – Sergey A Kryukov Commented Mar 17 at 16:59
  • hi thanks for the reply @mykaf. I still don't understand how to update the element's id. How do I do that? – purple hippo Commented Mar 17 at 17:12
  • 3 @purplehippo — You almost certainly shouldn't. See the XY problem. Why do you want to change the ID? – Quentin Commented Mar 17 at 17:13
  • 1 You wouldn't want to modify it because it's meant to be a unique identifier for that record. Changing it defeats that purpose. If you're not using it for that purpose, what are you using it for? Perhaps there is another attribute that would work better. – mykaf Commented Mar 17 at 17:20
  • 1 “...why is it a bad idea to modify id..?” Because there are simple and efficient techniques, not as messy as that, not even close. Look at this answer. I completely agree: you are trying to solve an XY Problem. If you don't clearly see what is a bad idea, you have to develop judgment and, for that matter, listen to the arguments carefully. I hope I won't need to explain why the id modification is bad, it would be too boring... – Sergey A Kryukov Commented Mar 17 at 17:53
 |  Show 3 more comments

1 Answer 1

Reset to default 5

Frame challenge: This is an XY Problem. The real problem is that you want to create an input and a label, and use a for attribute to link them. This requires that they have a unique ID.

Currently, you are counting the number of rows in the table to generate a number to use in the unique ID, and this is failing when you delete rows (because you already have an element with the ID generated when there were previously a smaller number of rows).

To solve this don't use the length in the ID, use some other value.

A simple solution would be to create a new variable:

let idCounter = 0; // Scoped outside the function so it persists between calls
function addRow() {

and then whenever you need to generate an ID

const myId = `eval_cb0_${++idCounter}`;

If you wanted unique IDs which could persist across pages, then you could look at using a library like uuid instead.

发布评论

评论列表(0)

  1. 暂无评论