Use of Button OnClientClick and Attributes Property

vishalneeraj-24503
Posted by vishalneeraj-24503 under JavaScript category on | Points: 40 | Views : 2004
Suppose, we want to perform validations through Javascript or want to fill dropdownlist in button click, or call any Javascript function in Button Click, so we can do it either by Button' OnClientClick Property or by Attributes property.

We can understand this by example:-

Suppose, i want to perform validations like this,

<script type="text/javascript">
function validate_controls()
{
var txt_f_name = document.getElementById('<%=txt_first_name.ClientID%>');
var txt_l_name = document.getElementById('<%=txt_last_name.ClientID%>');
var ddl_gender = document.getElementById('<%=ddl_gender.ClientID%>');

if(txt_f_name!=null && txt_l_name!=null && ddl_gender!=null)
{
if(txt_f_name.value.length<=0 || txt_f_name.value=='')
{
alert('First Name can not be empty');
return false;
}

if(txt_l_name.value.length<=0 || txt_l_name.value=='')
{
alert('Last Name can not be empty');
return false;
}

if(ddl_gender.selectedIndex==0)
{
alert('Please select Gender');
return false;
}
}
}
</script>

<asp:TextBox id="txt_first_name" runat="server"></asp:TextBox>

<asp:TextBox id="txt_last_name" runat="server"></asp:TextBox>

<asp:DropDownList id="ddl_gender" runat="server">

<asp:ListItem Text="--Select--" Value="0">--Select--</asp:ListItem>
<asp:ListItem Text="Male" Value="1">Male</asp:ListItem>
<asp:ListItem Text="Female" Value="2">Female</asp:ListItem>

</asp:DropDownList>

//NOW WE CAN VALIDATE CONTROLS IN 2 WAYS
1). EITHER BUTTON' ONCLIENTCLICK PROPERTY
2). OR ATTRIBUTES PROPERTY


<asp:Button id="btn_validate" runat="server" text="Validate Controls"
OnClientClick="validate_controls();"></asp:Button>

OR IN THE PAGE LOAD WE CAN WRITE
Protected void Page_Load()
{
if(!isPostback)
{
btn_validate.Attributes.Add("onclick","validate_controls()");
}
}

So by OnClientClick or Attributes Button property we can call any Javascript functions.

Comments or Responses

Login to post response