Archive for July 21, 2006

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

C#

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.

July 21, 2006 at 7:50 am 12 comments


Top Clicks

  • None

Calendar

July 2006
M T W T F S S
    Aug »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Recent Posts

Feeds

Blog Stats

  • 92,980 hits