Friday, July 21, 2006


Asp.NET : Page post back after JavaScript code executed on server control click

I created a ASP.NET page with two text boxes and a button. I want this button to reset the form(Only to reset the page). There are two ways you can do this, one is going to the click event of the button and add the code to clear the text boxes. Like the one given below


protected void Button1_Click(object sender, EventArgs e)


TextBox1.Text = string.Empty;

TextBox2.Text = string.Empty;


but this technique is very heavy, bcz it need another round trip to the server.

The other way is using the JavaScript. You need to add an attribute to the button in the page load event. Like this

protected void Page_Load(object sender, EventArgs e)


Button1.Attributes.Add(”onclick”, “JavaScript:document.forms[0].reset(); return false;“);


what this code does is that, The button is rendered like this

<input type=”submit” name=”Button1″ value=”Button” onclick=”JavaScript:document.forms[0].reset(); return false;” id=”Button1″ />

so that the page wiill be automatically reset when the user clicks the button (Completely handled by the browser, no round trip to the server).

The code that I bolded (return false;), its very important, other wise the page will be posted back.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?