1

The user inputs some text into a form and its stored in a variable 'userInput' I have html table with id="myTable". I want to iterate through the table using Javascript and delete all the rows where the value of the 3rd column in a row isn't equal to the userInput, but my code isn't working for some reason:

var theTable = document.getElementById("myTable");
for(int x = 0; x < theTable.rows.length; x++){
     if(theTable.rows[x].cells[2].innerHTML != userInput){
          theTable.deleteRow(x);
      }
}

3 Answers 3

3

The first issue with this code that I see is that you are deleting rows in a forward moving loop, meaning if you delete row 3, row 4 will now be 3 etc (not an issue if only deleting a single row but not a good practice).. You should delete in reverse ordered loop.

Also, you should probably compare the innerText vs innerHTML, I doubt the user input is HTML.

for(var x = theTable.rows.length; x > 0 ; x--){
  if(theTable.rows[x - 1].cells[2].innerText!= userInput){
      theTable.deleteRow(x -1);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also content of the cells might be formatted? E.g. <b>asdf</b> != asdf
1
  1. In your for loop you need to change int x to var x to be valid in javascript.
  2. To make sure, that every line is deleted, to only count up the iterator x, if a row was not deleted. (see the else statement)

var userInput = 'keep me';

var theTable = document.getElementById("myTable");
for(var x = 0; x < theTable.rows.length;){
  if(theTable.rows[x].cells[2].innerHTML != userInput){
    theTable.deleteRow(x);
  } else {
    x += 1;
  }
}
<table id="myTable">
  <tr>
    <td>text</td>
    <td>text</td>
    <td>keep me</td>
  </tr>
  <tr>
    <td>text</td>
    <td>text</td>
    <td>delete me</td>
  </tr>
  <tr>
    <td>text</td>
    <td>text</td>
    <td>delete me</td>
  </tr>
  <tr>
    <td>text</td>
    <td>text</td>
    <td>delete me</td>
  </tr>
</table>

Comments

0

try logging the outputs:

var theTable = document.getElementById("myTable");
for(int x = 0; x < theTable.rows.length; x++){
     console.log(theTable.rows[x].cells[2].innerHTML , userInput);
     if(theTable.rows[x].cells[2].innerHTML != userInput){
          theTable.deleteRow(x);
      }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.