Posted by: Vijay Modi | June 8, 2007

Button onClick and onClientClick

Today I got a comment regarding what is the difference between onClick and onClientClick. So I think to write a small article on it.     

Please find the following code for. I write the code for .aspx page. Copy and paste this code in your aspx page.

========================================================================================

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Untitled Page</title>
<script language=”javascript” type=”text/javascript”>
function confirmthis()
{
if(confirm(”Do you want to do a server trip?”))
{
return true;
}
else
{
return false;
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” OnClientClick=”return confirmthis();” Text=”Click Me…” /></div>
</form>
</body>
</html>

========================================================================================

Copy and paste following code in your code behind(aspx.cs) page.

========================================================================================

protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
         TextBox1.Text=”U click Button1″
}

========================================================================================

Now run your project. just Click on the button “Click Me…”. It will ask to “Do you want to do a server trip?”. If you select YES then you will do a server trip and when you select NO you will not redirect to server. So here for validation purpose we are using onClientClick and for doing process on server side, we are using onClick.
Best Regards,
Vijay Modi

Responses

How would you do this then:

When user clicks the button it should immediately get disabled (prevent anymore clicking) then call a serverside function (buttonclick event)???

On the lines of

Is there a way of getting this to work at all?

Jscript only does:
form[0].Button1.disabled = true;

asp:button id=”Button1″ runat=”server” OnClientClick=”return confirm(’Ok to post?’)” onclick=”btnOk_Click” Text=”Click!”

I have been loosing my precious time for more than 5 hours looking for a “good” answer to a problem related to this issue. I have just solved it. Thanks.

I think you got your answer. Let me know if you have any issue.

Thank you Vijay your sample code and great explanation helped me a lot.

I am at present studying Website Design, I think
I will bookmark your page for future reference.

Thanks again,

Kieran

Leave a response

Your response:

Categories