Monday, December 29, 2014

How to Validate Dropdownlist using JavaScript in HTML, Asp.net

Introduction:

Here I will explain how to validate dropdownlist using JavaScript in asp.net or html or dropdownlist validation using JavaScript in html or asp.net. To validate dropdownlist first we need to get selected value of dropdown based on that we can raise validation message.

 Validate Dropdownlist

To validate dropdownlist we will write code like as shown below here we will get dropdownlist selected value and check if it matching with first option value because first option value if we give it as “zero” we can compare value easily and raise validation
<script type="text/javascript">
function ValidateDropdown() {
var result = document.getElementById('<%=ddlEducation.ClientID%>').value;
if (result == "0") {
alert("Please Select Education");
}
else {
alert("Dropdownlist Selected Value is: " + result);
}
}
</script>
 
For Complete example the code like as shown below:
Validate Dropdownlist using Javascript in HTML:
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Dropdownlist using JavaScript</title>
<script type="text/javascript">
function ValidateDropdown() {
var result = document.getElementById('<%=ddlEducation.ClientID%>').value;
if (result == "0") {
alert("Please Select Education");
}
else {
alert("Dropdownlist Selected Value is: " + result);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Select Education:
<asp:DropDownList ID="ddlEducation" runat="server">
<asp:ListItem Value="0" Text="--Select Education--" />
<asp:ListItem Value="B.Tech" Text="BCIT" />
<asp:ListItem Value="MCA" Text="MCA" />
<asp:ListItem Value="MBA" Text="MBA" />
<asp:ListItem Value="BSIT" Text="BSIT" />
<asp:ListItem Value="MBBS" Text="MBBS" />
</asp:DropDownList>
<input type="button" value="Validate Dropdown" onclick="ValidateDropdown()" />
</div>
</form>
</body>
</html>
 
asp.net dropdownlist control 
 asp.net dropdownlist control we can use same code but only getting dropdownlist value in JavaScript code will change because in JavaScript we can identify asp.net controls by adding ClientID  
 
 

No comments:

Post a Comment