简体   繁体   中英

How to get the checked status from checkbox linked to label [Javascript]

I have a label linked to a checkbox like this.

    <asp:CheckBox runat="server" ID="chk1" />
    <asp:Label ID="lbl1" runat="server" AssociatedControlID="chk1" onclick="verifyCheck('lbl1', 'chk1')" />  

My javascript function

<script type="text/javascript">
    function verifyCheck(label, checkbox)
    {
        var labelCtrl = document.getElementById(label);
        var checkboxCtrl = document.getElementById(checkbox);
        labelCtrl.style.background = checkboxCtrl.checked ? alert('1') : alert('2');
    }

</script>

So, when I click on the label it works the check under the checkbox but the javascript does not return the real value from checkbox. It's too late. javascript executes and the checkbox changes its status later visually. So how can I do to change this approach to get at the moment of the click the real status from checkbox. So my alerts do the inverse reaction.

You have to listen for the onchange event on the checkbox, which is still fired when you click the label

<asp:CheckBox runat="server" ID="chk1" onchange="verifyCheck('lbl1', 'chk1')"/>
<asp:Label ID="lbl1" runat="server" AssociatedControlID="chk1" />

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