I need to validate a DropDownList in an ASP.NET project and am trying to use JavaScript even though I have never used it before.
I’m using the following ASP declaration and code JavaScript:
ASP declaration:
<asp:DropDownList ID="ddl1" runat="server" onprerender="ddl1_PreRender" ValidationGroup="AddNewCollection">
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Choose Type!"
ControlToValidate="ddl1" ForeColor="Red" ValidationGroup="AddNewCollection" ClientValidationFunction="clientSideCheckValue"></asp:CustomValidator>>
JavaScript code:
<script type="text/javascript">
function clientSideCheckValue(source, args)
{
var result1 = args.Value;
var rsult2 = document.getElementById("ddl1").value;
if (result2 == null) {
args.IsValid = false;
return true;
}
args.IsValid = true;
}
</script>
I have two questions about code mentioned above:
1.Why when I’m printing this row’s code var result1 = args.Value; intelisense dosen’t give me option to choose “Value” extension.
2.At this line of JavaScript code var rsult2 = document.getElementById(“ddl1”).value;
I get this error message Microsoft JScript runtime error: Object required.Have you got any idea why i meet this problem and how can i fix it?
Thank you in advance.
@Paul: “intelisense has no way of knowing what properties/methods args has, so it can’t give you the option.” Absolutely correct.
@Michael:
Assuming your JavaScript is in the .aspx markup, change your line to var rsult2 = document.getElementById(“<%=ddl1.ClientID” %>).value;. That will render the actual client ID of your DropDownList inside the script block.
Also, you appear to be just making sure an option has been picked. It’s a lot easier to add an
<asp:RequiredFieldValidator />and set theControlToValidateproperty to “ddl1” if that’s all you want to do.Hope this helps.