简体   繁体   中英

How to delete a row in the table when I click on a button? Using Javascript

HTML from with table and button:

<div>
                <h1>Info</h1>
                <form>
                    <table id="t">
                        <tr>
                            <th></th>
                            <th>index</th>
                            <th>name</th>
                            <th>job</th>
                            <th>date</th>
                            <th>department</th>
                        </tr>
                        <tr>
                            <td><input type="checkbox"></td>
                            <td>1</td>
                            <td>Alex</td>
                            <td>Hacker</td>
                            <td>100000000000000000</td>
                            <td>2</td>
                        </tr>
                    </table>
                    <br/>
                    <input type="submit" value="delete" onclick="deleteRow()">
                </form>
        </div>

I want to remove rows, which have establishes checkbox. Delete should be at the click of a button.

Javascript function that should delete:

function deleteRow() {
    let table = document.getElementById('t')
    let boxs = table.getElementsByTagName("input")
    for (i = 0; i < boxs.length; i++){
        if(boxs[i] == true) {
            table.deleteRow((boxs[i].parentNode.parentNode).rowIndex)
        }
    }
}

I debugged this code, the size of the array defined correctly, but doesn't enter to condition.

In you code you don't need to change much. You need to change if statement like below.

From

if(boxs[i] == true) {

}

To

if(boxs[i].checked == true) {

}

Because box[i] is object. So If you want to get the check status you need to call boxs[i].checked. This will give you true/false.

 function deleteRow() { let table = document.getElementById('t') let boxs = table.getElementsByTagName("input") for (i = 0; i < boxs.length; i++){ if(boxs[i].checked == true) { table.deleteRow((boxs[i].parentNode.parentNode).rowIndex) } } return false; } 
 <div> <h1>Info</h1> <form onsubmit="return deleteRow()"> <table id="t"> <tr> <th></th> <th>index</th> <th>name</th> <th>job</th> <th>date</th> <th>department</th> </tr> <tr> <td><input type="checkbox"></td> <td>1</td> <td>Alex</td> <td>Hacker</td> <td>100000000000000000</td> <td>2</td> </tr> </table> <br/> <input type="submit" value="delete"> </form> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM