Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2011-09-13
9
Medium Priority
?
345 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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
 
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 1000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Loops Section Overview
Suggested Courses

824 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