Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing html table row values indexes with pure Javascript

I have a scenarion where I delete rows in a html table. Once the row is deleted, I am trying to realign/sort the hidden fields indexes. for example if second row with hidden fields name[1]abc tr is deleted, then I am trying to generate table with rows having hidden fields with index name[0] and name[1] etc., Any pointers ?

My fiddle

<table class="links-list">
  <tbody>
    <tr>
      <td>test1</td>
      <td>test2</td>
      <input type="hidden" name="name[0]abc">
      <input type="hidden" name="name[0]def">
      <input type="hidden" name="name[0]gh1">
    </tr>
    <tr>
      <td>test1</td>
      <td>test2</td>
      <input type="hidden" name="name[1]abc">
      <input type="hidden" name="name[1]def">
      <input type="hidden" name="name[1]gh1">
    </tr>
    <tr>
      <td>test1</td>
      <td>test2</td>
      <input type="hidden" name="name[2]abc">
      <input type="hidden" name="name[2]def">
      <input type="hidden" name="name[2]gh1">
    </tr>
  </tbody>
</table>

Javascript

//Loop through table rows
//get all hidden fields for each row
// update index value inside name[index] in sorted order
// like all hidden fields with name[0] in first row name[1] for second row etc
function updateHyperlinkIndexes() {
  var linksList = document.querySelector('.links-list tbody');
  for (var i = 1; i < linksList.children.length; i++) {
    var trContent = linksList.children[i];
    for (var i = 0; i < trContent.children.length; i++) {
      if (trContent.children.item(i).type && trContent.children.item(i).type === "hidden") {
        var cellName = trContent.children.item(i).name;
        trContent.children.item(i).name = cellName.replace(/[.*]/, i);
      }
    }
  }
  return linksList;
};

var updatedHtml = updateHyperlinkIndexes();
like image 371
Kurkula Avatar asked Feb 03 '18 01:02

Kurkula


1 Answers

Found the problem, PFB working updateHyperlinkIndexes() function.

var linksList = document.querySelector('.links-list tbody');
  for (var i = 0; i < linksList.children.length; i++) {
    var trContent = linksList.children[i];
    for (var j = 0; j < trContent.children.length; j++) {
      console.log(trContent.children[j]);
        if (trContent.children.item(j).type && trContent.children.item(j).type === "hidden") {
        var cellName = trContent.children.item(j).name;
        trContent.children.item(j).name = cellName.replace(/\[.*?\]/g, '['+i+']');
      }
    }
  }

Changes made include correction of replace regex expression, it should be replace(/\[.*?\]/g, '['+i+']');. And secondly you used same variable i for iterating nested loops.

Hope it helps you.

like image 139
Mohd Asim Suhail Avatar answered Oct 16 '22 21:10

Mohd Asim Suhail