Geeks With Blogs
Hani Amr

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>

Posted on Thursday, March 10, 2011 12:05 AM Sharepoint 2010 , Javascript | Back to top

Copyright © H@Ni | Powered by: GeeksWithBlogs.net