Monday, May 2, 2011

Handling HTML checkbox in AJAX

This post will teach you how to check and uncheck all the checkbox in a table using a toggle checkbox.

I have created 3 functions below.
  • check_toggle - this will toggle checkbox whether check all or uncheck all.
  • check_all - this will check all the checkbox in the form.
  • uncheck_all - this will uncheck all the checkbox in the form.
Please see implementation below.

<script type="text/javascript">

function check_toggle() {
        var obj = document.frmdata.checkbox_toggle;
        if (obj.checked==true) {
                check_all();
        } else {
                uncheck_all();
        }
}

function check_all() {
        var obj = document.frmdata.checkbox
        if (!obj.length) {
                obj.checked = true
        } else {
                var x = 0;
                for (x = 0; x <= obj.length; x++) {
                        obj[x].checked = true
                }
        }
}

function uncheck_all() {
        var obj = document.frmdata.checkbox
        if (!obj.length) {
                obj.checked = false
        } else {
                var x = 0;
                for (x = 0; x <= obj.length; x++) {
                        obj[x].checked = false
                }
        }
}

</script>

<form id="frmdata" name="frmdata">
<table>
        <tr>
                <td><input type="checkbox" name="checkbox_toggle" id="checkbox_toggle" onclick="check_toggle();"></input></td>
                <td>Description</td>
        </tr>
        <tr>
                <td><input type="checkbox" name="checkbox" id="checkbox"></input></td>
                <td>Row 1</td>
        </tr>
        <tr>
                <td><input type="checkbox" name="checkbox" id="checkbox"></input></td>
                <td>Row 2</td>
        </tr>
         <tr>
                <td><input type="checkbox" name="checkbox" id="checkbox"></input></td>
                <td>Row 3</td>
        </tr>
</form>

No comments:

Post a Comment