Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row when checking checkbox in html table

I have a HTML table with a checkbox in one of the columns. I want to know how I could get the row data when the user clicks on the checkbox with javascript (without jquery)? Can anyone please help me with this?

Thanks

like image 955
user1145581 Avatar asked Aug 28 '13 11:08

user1145581


People also ask

How do you find a row in a table in HTML?

The <tr> HTML element defines a row of cells in a table.

How do you check whether a checkbox is checked or not in a table?

change(function () { if ($("input[type='checkbox']:checked"). length > 0) $("#b1"). prop("disabled", false); else $("#b1"). prop("disabled", true); });


2 Answers

You could try something like this:

HTML:

<table>
    <thead>
        <tr><th></th><th>Row Text</th></tr>
    </thead>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Test</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Test 2</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Test 3</td>
    </tr>
</table>

JavaScript:

checkboxes = document.getElementsByTagName("input"); 

for (var i = 0; i < checkboxes.length; i++) {
    var checkbox = checkboxes[i];
    checkbox.onclick = function() {
        var currentRow = this.parentNode.parentNode;
        var secondColumn = currentRow.getElementsByTagName("td")[1];

        alert("My text is: " + secondColumn.textContent );
    };
} 

JSFiddle: http://jsfiddle.net/markwylde/wzPHF/1/

like image 30
Mark Avatar answered Sep 28 '22 03:09

Mark


HTML DOM solves your problem

<script type="text/javascript">
    function getRow(n) {
        var row = n.parentNode.parentNode;
        var cols = row.getElementsByTagName("td");
        var i=0;
        while (i < cols.length) {
            alert(cols[i].textContent);
            i++;
        }
    } 
</script>

<table>
    <tr>
        <td><input type="checkbox" onclick="getRow(this)"  /></td>
        <td>aaa</td>
        <td>bbb</td>
    </tr>
    <tr>
        <td><input type="checkbox" onclick="getRow(this)" /></td>
        <td>ccc</td>
        <td>ddd</td>
    </tr>
    <tr>
        <td><input type="checkbox" onclick="getRow(this)" /></td>
        <td>eee</td>
        <td>fff</td>
    </tr>
</table>

EDIT: this script will help you more, I think:

function getRow(n) {
    var row = n.parentNode.parentNode;
    var cols = row.getElementsByTagName("td");
    var i = 0;

    while (i < cols.length) {
        var val = cols[i].childNodes[0].nodeValue;
        if (val != null) {
            alert(val);
        }

        i++;
    }
}
like image 119
Harutyun Imirzyan Avatar answered Sep 28 '22 02:09

Harutyun Imirzyan