Validate that a Checkbox is checked using javascript

Posted by H(at)Ni on Geeks with Blogs See other posts from Geeks with Blogs or by H(at)Ni
Published on Thu, 10 Mar 2011 12:05:37 GMT Indexed on 2011/03/10 16:11 UTC
Read the original article Hit count: 258

Filed under:

I was facing a challenge yesterday that I was creating a Visual webpart and I wanted to validate the a submit button is only visible if the user checked a "I agree to terms" checkbox.

Something was weired that I tested my code on a normal asp.net website and it worked perfectly while it had a different behaviour inside the webpart which is whenever I check the checkbox, the button is enabled but it will not fire the asp.net validators in client side. It posts back the page and then the validators appear after that.

So, I tried to change my type of thinking and I reached a different solution is that to call a javascript function whenever the button is clicked and then check if the checkbox is clicked or not.

To illustrate more, here are an example to what I'm saying:

1. Button in aspx page:

<asp:Button OnClientClick="CheckForCondition();"  ValidationGroup="CompaniesSection" ID="btnCompaniesSubmit"
                        runat="server" Text="Submit" />

2. CheckForCondition() function:

<script language="javascript" type="text/javascript">
                        function CheckForCondition() {
                            if ($jq('#<%= ChkCompanyCheck.ClientID %>:checked').val() == undefined) {
                                $jq('#lblCheckBox').show();
                                return false;
                            }
                            else {
                                $jq('#lblCheckBox').hide();
                                return true;
                            }

                        }
                     </script>

3. lblCheckBox is simply a label that shows a red asterisk beside the checkbox to indicate that it's a required field.

<label id="lblCheckBox" style="color:Red;display:none">*</label>

© Geeks with Blogs or respective owner