Solved

What is the best way to clear controls on an ASP.NET form

Posted on 2011-09-13
9
324 Views
Last Modified: 2012-05-12
Hi,

After data is entered on a web form and then comitted to a database or whatever, what is the best way to clear the contents of the various text box controls and return combo boxes to a non-selected state?  I know this can be done from the code behind but is not the best way since it requires a round trip to the server.  I know javascript is also an option but I am not very familiar with it at all so is there another option or is Javascript the best way?

Thanks
0
Comment
Question by:obb-taurus
9 Comments
 
LVL 16

Expert Comment

by:SriVaddadi
ID: 36533456
You could jQuery javascript library. It provides each function something similar to for each in C#
check this
http://api.jquery.com/each/
0
 
LVL 2

Expert Comment

by:sanjaysumantera
ID: 36533470
You can check this Link:
Clear form Field
I hope this will help you.

Sanjay M Suman
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 36533661
If you don't want to go back to the server, then javascript is pretty much your only option.  If you use jQuery (which is a javascript library that makes writing javascript easier) it can be pretty quick too.  Example below:

<html>
<head>
   <title>My Website</title>
   <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
   <script type="text/javascript">
         $(document).ready(function()
         {
                $('#submit-button').click(function()
                {
                      $('#form1').find('input[type="text"]').val('');  //clears all text textbox controls
                      $('#form1').find('input[type="textarea"]').val('');  //clears all text multiline textboxes
                      $('#form1').find('select').val(-1);  //sets the selected index of all drop down lists to -1;
                });
         });
   </script>
</head>
<body>
   <form id="form1" runat="server">
       
   <!-- your asp.net form controls here (i.e. textbox, combobox etc.) -->

    <input type="submit" id="submit-button" />

   </form>
</body>
</html>
0
 

Author Comment

by:obb-taurus
ID: 36540056
The web application I'm building utilizes a master page with content pages and I would like to have a seperate file (.js) to contain the script(s).  How would I call the javascript function when a button is clicked on my content page?

Thanks
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 36546194
In the <head> section of your master page include a link to jQuery. You'll probably want to be using jQuery on most of your content pages (in one form or another), so placing it on your master page makes perfect sense, as it is then accessible to all your content pages.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>


Then create a new javascript file (.js) and name it whatever you want (e.g. "my-custom-script.js") and add the following javascript to this newly created script file:

$(document).ready(function()
{
         $('#submit-button').click(function()
         {
                 $('#form1').find('input[type="text"]').val('');  //clears all text textbox controls
                 $('#form1').find('input[type="textarea"]').val('');  //clears all text multiline textboxes
                 $('#form1').find('select').val(-1);  //sets the selected index of all drop down lists to -1;
         });
});

Then you just need to include a link to this custom script file, similar to how you included the jQuery library above.  You can include this script on the master page as well (if you think you will be using it on several content pages), or you can include it on your content page, if you only want the script to be loaded by the client browser when a user navigates to that specific content page:

<script type="text/javascript" src="script/my-custom-script.js"></script>

If you include it on your master page, make sure that you include it AFTER you include the jQuery, as your custom script relies on jQuery being loaded first:

Right way:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="script/my-custom-script.js"></script>

Wrong way:
<script type="text/javascript" src="script/my-custom-script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
0
 

Author Comment

by:obb-taurus
ID: 36546684
Hi P1ST0LPETE,

I added the code as you instructed but the function does not seem to fire.  For simplicity sake I added the to script lines to my master page and then created a .js file with the code you supplied (altered the code to match my button name) but nothing happens.  I even put an alert in the function just to be sure and the alert doesn't even show up.  I also noted that if I tried to put the script line that defines the location of my .js file in the content page, VS 2010 gave me a warning saying it shouldn't be there which was the other reason I moved it over to my master page.

Any thoughts?

Thanks
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 36547297
To test that jQuery is actually working properly have the <head> section on your master page look like this:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
      $(document).ready(function()
      {
             alert('jquery is working');
      });
</script>


Then take the following code and place it in your external .js file to test if you are properly linking to the external .js file:
$(document).ready(function()
{
        alert('jquery is working');
});


If you get the alert the 2nd time then you have jquery setup properly, and so your problem is probably an improper syntax issue.

So going off a guess (as I can't see your code), you're probably not providing a proper selector for jQuery to hook an event to your button click.

If your button looks like this:  <input type="submit" id="submit-button" />
Then you need a jquery selector that looks like this:    $('#submit-button')
Note the # sign before the name, which tells jquery that you are looking for an ID attribute

However, if your button looks like this: <input type="submit" name="foo-bar" />
Then you need a jquery selector that looks like this:   $('[name*="foo-bar"]')
We are now telling jquery to find the element by it's name.

Have a look here to see all the ways you can select an element with jquery: http://api.jquery.com/category/selectors/
0
 

Author Comment

by:obb-taurus
ID: 36556931
Hi P1ST0LPETE,

I have verified JQuery is actually working on my system but when I try the code to clear the various controls it doesn't do anything.  I've verified the jQuery function is being triggered by setting a breakpoint at the jQuery function unfortunately I can't make heads or tails out of the jQuery code that I'm stepping through in break mode.

Could there be something else I'm missing?

Thanks
0
 
LVL 10

Accepted Solution

by:
P1ST0LPETE earned 250 total points
ID: 36564671
Not sure what is going wrong for you, however  I've got an example here that I just wrote and tested.
Also, there were a couple brain farts of my own in the code above.

1.  $('#form1').find('input[type="textarea"]').val('');  will not clear multiline textboxes and needs to be changed to
$('#form1').find('textarea').val('');

2.  $('#form1').find('select').val(-1);  will not clear the selection on a dropdownlist, and needs to be replaced with
$('#form1').find('select').prop('selectedIndex', -1);


Complete Working Example:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $('#submit-button').click(function ()
            {
                $('#form1').find('input[type="text"]').val('');  //clears all text in textbox controls
                $('#form1').find('textarea').val('');  //clears all text in multiline textboxes
                $('#form1').find('select').prop('selectedIndex', -1);  //sets the selected index of all drop down lists to -1;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox4" runat="server" TextMode="MultiLine"></asp:TextBox>
        <asp:TextBox ID="TextBox5" runat="server" TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Value="1" Text="Item 1" />
            <asp:ListItem Value="2" Text="Item 2" />
            <asp:ListItem Value="3" Text="Item 3" />
        </asp:DropDownList>
        <br />
        <asp:ListBox ID="ListBox1" runat="server">
            <asp:ListItem Value="1" Text="Item 1" />
            <asp:ListItem Value="2" Text="Item 2" />
            <asp:ListItem Value="3" Text="Item 3" />
        </asp:ListBox>
        <br />
        <input type="button" id="submit-button" value="click me" />
    </div>
    </form>
</body>
</html>

Open in new window



However, an even cleaner and object oriented approach would be to use this jQuery plugin I just wrote:
 
$.fn.clear = function ()
{
    return this.each(function ()
    {
        switch (this.tagName.toLowerCase())
        {
            case 'form': return $(':input', this).clear(); break;
            case 'textarea': this.value = ''; break;
            case 'select': this.selectedIndex = -1; break;
            case 'input':
                switch (this.type)
                {
                    case 'text':
                    case 'password': this.value = ''; break;
                    case 'radio':
                    case 'checkbox': this.checked = false; break;
                }
            break;
        }
    });
};

Open in new window


Simply create a new .js file named something like "clear-form.js" and paste the above plugin code into it.
This will allow you to use the power of jQuery and clear any input by passing in the selector, like this:

<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="script/clear-form.js" ></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $('#submit-button').click(function ()
            {
                $('form').clear();
            });
        });
    </script>
</head>

Or if you want to clear a certain textbox (or whatever) you can just pass in the specific selector like this:
$('#id).clear();
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now