简体   繁体   中英

Why am I not able to untick this checkbox using JavaScript?

My ASP code is as follows:

<asp:CheckBox ID="chk" runat="server" Checked="false"/>

And in my JavaScript:

document.getElementById('chk').checked = result.isUserSpecific;
    if (result.isUserSpecific === 'False') {
        document.getElementById('chkUserSpecific').checked = 'False';
    }

I'm currently able to tick the checkbox through JavaScript when the result is true but I can't seem to untick the box.

I've tried changing 'False' to 'false' and it appears that the result being returned is definitely False. Any pointers would be welcome.

You need to assign a boolean value to the checked property, not a string.

false or true not 'False' and not 'false' .

'false' and 'False' are both true values when coerced into a boolean.

ASP.NET ensures HTML id attributes are unique on its controls by prefixing them. What you're declaring as chk is being converted to something like c100_c100_chk before being added to your page.

The easiest way to support this would be to use document.querySelector() , passing in an attribute selector which matches the end of your element's ID:

document.querySelector('[id$="chk"]').checked = ...;

Furthermore, the string value 'False' is a truthy value and will evaluate to true . You need to set this to false , not 'False' :

document.getElementById('chkUserSpecific').checked = false;

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