2010-08-31 102 views
1

ASP.NET3.5 Webforms。我試圖把驗證器放在下拉列表中,只有當複選框被選中。驗證DropDownList如果選中複選框

這不起作用。如果我在onclick事件中發出警報,它會顯示。

<script language="javascript" type="text/javascript"> 
    function setVal(sender) { 
     var myVal = document.getElementById('<%=(DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ddlSupplierCouncilArea")%>'); 
     ValidatorEnable(myVal, !sender.checked); 
     ValidatorValidate(myVal) 
    } 
</script> 

<asp:CheckBox runat="server" ID="cbxIsSupplier" Text="I wish to register as a Supplier in the" 
            OnClick="setVal(this)" /> 

<asp:DropDownList ID="ddlSupplierCouncilArea" runat="server"> 
            <asp:ListItem>[Please select]</asp:ListItem> 
            <asp:ListItem Value="blah1">blah1</asp:ListItem> 
            <asp:ListItem Value="Waimakariri">blah2</asp:ListItem> 
           </asp:DropDownList> 
           <div class="validators"> 
            <asp:RequiredFieldValidator ID="rfvCouncilArea" runat="server" InitialValue="[Please select]" 
             ControlToValidate="ddlCollectorCouncilArea" ErrorMessage="Select a Council Area" 
             Enabled="false" ToolTip="Select a council area" ValidationGroup="CreateUserWizard1">* required</asp:RequiredFieldValidator> 
           </div> 

回答

0

您可以使用Firefox的Firebug插件來調試您的JavaScript代碼,它使生活更輕鬆。

反正你可以重寫你的函數類似這樣的

 
function setVal(sender, drpClientID) 
{ 
    var myVal = document.getElementById(drpClientID); 
     ValidatorEnable(myVal, !sender.checked); 
     ValidatorValidate(myVal) 
} 

In asp.net code you should build your onclick attribute like this

 
cbxIsSupplier.Attributes.Add("onclick", "setVal(this, '" + ddlSupplierCouncilArea.ClientID + "')"); 

+1

其他開發人員解決了這個我使用jquery這似乎是一個更好的選擇。 – 2010-10-14 22:34:18