views:

82

answers:

1

i use this javascript syntax for validating a checkbox...

 alert(document.getElementById("ctl00_ContentPlaceHolder1_Chkreg").checked);
  if (document.getElementById("ctl00_ContentPlaceHolder1_Chkreg").checked == false) {
        document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "please select the checkbox";
        document.getElementById("ctl00_ContentPlaceHolder1_Chkreg").focus();
        return false;
    }

My alert showed me false but my if loop is not working... Any suggestion...

+4  A: 

Assuming your box isn't checked, I would personally write it like:

var box = document.getElementById("ctl00_ContentPlaceHolder1_Chkreg");
if (!box.checked) {
    document.getElementById("ctl00_ContentPlaceHolder1_ErrorMsg").innerHTML = "please select the checkbox";
    box.focus();
    return false;
}
Jage
@jage that worked but what is wrong with my statement
bala3569
Perhaps, if your script ran when the page loaded, and maybe you hadn't checked the box before, that could possibly cause the checked variable to not be defined. Using the exclamation point checks this property using truthy / falsey technique. Something that is null or undefined will also be falsy. You usually fare better with that than checking if the property is actually equal to false.
Jage