Display the status of checkbox when checked or unchecked using JavaScript

Mohammed Imtiyaz Dec 27, 2014

Live Demo

Check / Uncheck the checkboxes to see the status.



This tutorial will explain you how to display the status of a ASP.Net / Html checkbox when it is checked or unchecked, using JavaScript. In this tutorial, we will use JavaScript function on ASP.Net Web Page and Html Page.

HTML Controls

<!DOCTYPE html>
<html>

<body>
    <div class="form-group">
        <input id="cbStatus1" type="checkbox" checked="checked" onclick="Function1();" />
        <label id="lblStatus1" style="color:green">Checked</label>
    </div>
    <div class="form-group">
        <input id="cbStatus2" type="checkbox" checked="checked" onclick="Function2();" />
        <label id="lblStatus2" style="color:green">Active</label>
    </div>
</body>

</html>

JavaScript Functions

<script language="javascript" type="text/javascript">
    function Function1() {
        var cbStatus1 = document.getElementById('cbStatus1');
        var lblStatus1 = document.getElementById('lblStatus1');

        if (cbStatus1.checked == true) {
            lblStatus1.innerHTML = "Checked";
            lblStatus1.style.color = "Green";
        } else {
            lblStatus1.innerHTML = "Unchecked";
            lblStatus1.style.color = "Red";
        }
    }

    function Function2() {
        var cbStatus2 = document.getElementById('cbStatus2');
        var lblStatus2 = document.getElementById('lblStatus2');

        if (cbStatus2.checked == true) {
            lblStatus2.innerHTML = "Active User";
            lblStatus2.style.color = "Green";
        } else {
            lblStatus2.innerHTML = "Inactive User";
            lblStatus2.style.color = "Red";
        }
    }
</script>

If the code is used on web page with server controls, then the server controls should be rendered as:

var cbStatus1 = document.getElementById('<%=cbStatus1.ClientID %>');
var lblStatus1 = document.getElementById('<%=lblStatus1.ClientID %>');