How to validate a dropdownlist using javascript?

Here I am proving a very simple solution for validate a dropdownlist using javascript.I hope that this will help many of the developers those who are troubling with dropdownlist validation.Now let us see How to validate a dropdownlist using javascript?.

<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>www.dotnetstock.com</title>
<script language="javascript">


function funSelect()
{
var obj=document.getElementById('<%=DropDownList1.ClientID %>');
if (obj.options.value=="")
alert("Please select a value from the DropdownList");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Select" Value=""></asp:ListItem>
<asp:ListItem Text="A" Value="a"></asp:ListItem>
<asp:ListItem Text="B" Value="b"></asp:ListItem>
<asp:ListItem Text="C" Value="c"></asp:ListItem>
</asp:DropDownList></div>
<asp:Button ID="btncheck" runat="server" text="Click" />
</form>
</body>
</html>




//add this part in Code-Behind (Default.aspx.cs) page load
btncheck.Attributes.Add("onclick", "return funSelect();");

 

— thank you !!

Leave a Reply

Your email address will not be published. Required fields are marked *