Kanhu
Kanhu

Reputation: 39

JavaScript and HTML

I want the javascript to check only elements from one table if checked the corresponding table's checkbox only. JavaScript i have selects all rows from all the tables generated from a cgi script.

You can see multiple tables with information listed. If you select the checkbox of any below geneID, it checks all even from the other tables contents too. one possible problem i figured out is i have assigned same table id for all the tables, but as this is auto generated from a previous cgi script, i certainly cant find any possible solution to overcome it. Thank you any suggestions or comments are highly accepted.

<script type="text/javascript" language="javascript">
    function SetAllCheckBoxes(ele) {
        var checkboxes = document.getElementsByTagName('input');
        if (ele.checked) {
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].type == 'checkbox') {
                    checkboxes[i].checked = true;
                }
            }
        } else {
            for (var i = 0; i < checkboxes.length; i++) {
                console.log(i)
                if (checkboxes[i].type == 'checkbox') {
                    checkboxes[i].checked = false;
                }
            }
        }
    }
</script>

Upvotes: 2

Views: 127

Answers (2)

Raef Kandil
Raef Kandil

Reputation: 307

If the code you cannot change, you need to get somehow the table element of the selected checkbox. In order to get that, you will have to alter the javascript function as follows:-

    <script type="text/javascript" language="javascript">
        function SetAllCheckBoxes(ele) {
            var checkboxes = ele.parentNode.parentNode.parentNode.getElementsByTagName('input');
            if (ele.checked) {
                for (var i = 0; i < checkboxes.length; i++) {
                    if (checkboxes[i].type == 'checkbox') {
                        checkboxes[i].checked = true;
                    }
                }
            } else {
                for (var i = 0; i < checkboxes.length; i++) {
                    console.log(i)
                    if (checkboxes[i].type == 'checkbox') {
                        checkboxes[i].checked = false;
                    }
                }
            }
        }
    </script>

First parentNode gets you the td, second parentNode gets you the tr, third parentNode gets you the table.

Upvotes: 1

James
James

Reputation: 22247

Since you have a separate form for each table you can make use of that to locate only the inputs on that form. Also you don't need the if - just set the checkboxes' checked states to that of ele.

function SetAllCheckBoxes(ele) {
    var checkboxes = ele.form.getElementsByTagName('input');
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].type == 'checkbox') {
            checkboxes[i].checked = ele.checked;
        }
    }
}

Upvotes: 1

Related Questions