Use of Dropdown Javasript Onchange Event

vishalneeraj-24503
Posted by vishalneeraj-24503 under JavaScript category on | Points: 40 | Views : 1815
If we want to avoid postback and instead of calling Dropdownlist' SelectedIndexChaned event,we can call Javascript OnChange event directly from from Aspx page.

We can understand this by an example:-

function show_message()
{
var ddl_gender = document.getElementById('<%=ddl_gender%>');

if(ddl_gender!=null)
{
if(ddl_gender.options[ddl_gender.selectedIndex].value.toUpperCase()=="SELECT")
{
alert('Please select any option");
return false;
}

if(ddl_gender.options[ddl_gender.selectedIndex].value.toUpperCase()=="MALE")
{
alert('Seleced option is Male");
return false;
}

if(ddl_gender.options[ddl_gender.selectedIndex].value.toUpperCase()=="FEMALE")
{
alert('Seleced option is Female");
return false;
}
}
}

<asp:DropDownList id="ddl_gender" runat="server" onchange="show_message();" >
<asp:ListItem Text="--Select--" Value="Select">--Select--</asp:ListItem>
<asp:ListItem Text="Male" Value="Male">Male</asp:ListItem>
<asp:ListItem Text="Female" Value="Female">Female</asp:ListItem>
</asp:DropDownList>

We can also call show_message() function from code-behind as

In Page_Load()
{
if(!IsPostBack)
{
ddl_gender.Attributes.Add("onchange","show_message();");
}
}

Comments or Responses

Login to post response