Monday, July 7, 2008

Dropdown validation using Javascript

The below code is for validating the dropdown when click on the submit button. I have described below step by step process.

Step 1:

function getcheckdrp()
{
var drp=document.getElementById("drpcheck");
if(drp=='[object]')
{
if(drp.selectedIndex==0)
{
alert("please select state");
return false;
}
}
}

step 2:

<asp:ListItem>----Select State----</asp:ListItem>
<asp:ListItem>Karnataka</asp:ListItem>
<asp:ListItem>Bangalore</asp:ListItem>
</asp:DropDownList>

<asp:Button ID="btncheckdrp" runat="server" />

step 3:

protected void Page_Load(object sender, EventArgs e)
{
btncheckdrp.Attributes.Add("onclick", "javascript:return getcheckdrp()");
}