Rory
Rory

Reputation: 41807

How to pass control.ClientId to an OnClick function in ASP.NET?

I'm trying to turn on/off various RequiredFieldValidator controls when checkboxes are checked/unchecked, based on this question. But rather than having a separate js function for each checkbox I want to pass in the ClientID of the input to validate, something like this (only one INPUT here but you can see once it's working I can add more INPUTs without more js):

<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" 
    OnClick="updateValidator('<%= rfvSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" 
    ErrorMessage="You must enter a subject." runat="server" />

 <script>
 function updateValidator(inputId) {
      var enableValidator = !event.srcElement.checked;
      var theInput = document.getElementById(inputId);
      ValidatorEnable(theInput, enableValidator);
 }
 </script>

Currently that scriptlet txtSubject.ClientID isn't evaluated, just output directly. I'm sure this is simple but I just don't know the appropriate syntax.

Upvotes: 2

Views: 14828

Answers (3)

Chris Snyder
Chris Snyder

Reputation: 968

How about adding it via the codebehind (or a script section):

checkSubjectRequired.Attributes.Add("onclick", "updateValidator(" + 
  txtSubject.ClientID + ")");

This explaination of ClientID may be helpful.

Upvotes: 2

Justin Harvey
Justin Harvey

Reputation: 14672

You could just do this:

    <asp:TextBox ID="txtSubject" runat="server" /> 
    <asp:CheckBox ID="chkSubjectRequired" runat="server"  
    OnClientClick="updateValidator(this.id);" /> 
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"  
    ErrorMessage="You must enter a subject." runat="server" /> 

 <script> 
 function updateValidator(inputId) { 
      var enableValidator = !event.srcElement.checked; 
      var theInput = document.getElementById(inputId); 
      ValidatorEnable(theInput, enableValidator); 
 } 
 </script>

Upvotes: 0

Mick Walker
Mick Walker

Reputation: 3847

This is because; ASP.NET parser can not parse server tag "<% = %>" for a server side control (i.e. control made as runat='server'). Use the following:

<asp:TextBox ID="txtSubject" runat="server" /> 
<asp:CheckBox ID="chkSubjectRequired" runat="server"  
    OnClick="updateValidator('<%#txtSubject.ClientID %>');" /> 
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"  
    ErrorMessage="You must enter a subject." runat="server" /> 

 <script> 
 function updateValidator(inputId) { 
      var enableValidator = !event.srcElement.checked; 
      var theInput = document.getElementById(inputId); 
      ValidatorEnable(theInput, enableValidator); 
 } 
 </script> 

Upvotes: 0

Related Questions