user1294886
user1294886

Reputation: 87

Deleting multiple selected table rows using only javascript

I would like to delete selected rows in a table using javascript but problem is that once a row is deleted the index changes.

This problem is confounded because only specific rows contain checkboxes and more checkboxes can be added.

I can already obtain all the correct row indexes I wish to delete inside of an array using javascript but then how would I then go about deleting the rows without hitting the wrong one and without using prototype or jquery. Purely javascript?

Any help is greatly appreciated.

 <table class="example_table" id="mytable">
    <tbody>
          <tr>
                <td><input type="text" id="top row" /></td>
          </tr>

          <tr>
                <td><input type="button" onclick="addNewCheckboxRow()" /></td> 
          </tr>

          <tr>
                <td><input type="button" /></td> 
          </tr>

          <tr>
                <td><input type="checkbox" value="1" id="check1" /></td>  //row that may be deleted
          </tr>

          <tr>
                <td><input type="checkbox" value="2" id="check2" /></td>  //row that may be deleted
          </tr>

          <tr>
                <td><input type="checkbox" value="3" id="check3" /></td>  //row that may be deleted
          </tr>
          <tr>
                <td><input type="checkbox" value="4" id="check4" /></td>  //row that may be deleted
          </tr>   

          <tr>
                <td><input type="button" /></td> 7
          </tr>
        </tbody>
    </table>

My current approach. not exact but you can get the drift.

var myrow=["6","7"];

document.getElementById("mytable").deleteRow(myrow[0]); //deletes row 6

document.getElementById("mytable").deleteRow(myrow[1]); //deletes row 7 But
                                                        //the index has changed!

//what happens when after the delete more rows are added!

Upvotes: 0

Views: 2137

Answers (1)

3on
3on

Reputation: 6339

Sort your Array from the bigger to the lower elements.

function compareNumbers(a, b)
{
  return b - a;
}

And then remove from the Biggest to the smallest.

Upvotes: 2

Related Questions