Friday, January 2, 2009
Example form
The example form
This is an example form. I play slightly false here: the form cannot be submitted because my present server doesn't allow CGI. Instead, I print out the values you filled in in the textarea and return false anyway, so the form isn't submitted.
The onSubmit script does two things: it checks whether you have filled in something in the four text boxes and it gathers name and value of all elements you have selected/checked and prints them out in the textarea below.
Name
Address
City
Why do you want to learn JavaScript? Dunno
Because my boss told me to
Generally interested
It might come in useful
How did you get to this site?
I'd like additional information about oranges
potatoes
tomatoes
blue whales
When you hit 'Submit' the user input will be written to this textarea
If you want to know exactly how this script works, please see the source. On this page I'll explain only the bit that checks if the text fields are filled in.
See the Form error messages script for a superior way of informing the user of form validation problems.
Checking text fields
This script checks whether the user has filled in anything in text fields. It ignores check boxes and radio buttons, but it will always ask the user to fill in a select box, even if he has already done so, because a select box always has a value of null. So it's best to use this script only when you want to check text fields.
function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}
In this example, I want to check elements 0-3, so I have a variable i that goes from 0 to 3. As you can see, I'm using numbers here instead of names. This is one of the cases in which it's better to use numbers than names.
for (i=0;i<4;i++) {
Then I make a variable box, which accesses the current form element. If I didn't create it, I'd have to write document.forms['example'].elements[i] a couple of times and I'm too lazy for that.
box = document.example.elements[i];
If the current text field has no value, the user has filled in nothing and we need to do several things.
if (!box.value) {
First we show an alert that uses the name of the text field. If you keep the names of your text fields logical, the user understands from this alert what text field should be filled in.
alert('You haven\'t filled in ' + box.name + '!');
As an additional service, we place the focus on the text field so that the cursor is in it and the user can start typing right away. Since all JavaScript browsers support focusing on form fields, we don't need a support detect.
box.focus()
Finally we return false. The script stops immediately and the form is not submitted. We wait for further user input.
return false;
If every text field has a value, we return true to show that everything is OK. Function stops, form is submitted and we're ready.
}
}
return true;
Introduction to Forms
I can't give you a complete script, because each form and each check are different. You'll have to use the elements I explain on this page to build your own script. I created an example form and script that you can study to get the hang of it.
On this page I discuss the limitations of using JavaScript to check a form, then I'll explain the onsubmit event handler, followed by the few methods and properties of the form itself. Then it's time for accessing the form elements and the specific syntax for accessing the user defined value of form elements.
See also Jeff Howden's excellent article Forms & JavaScript Living Together in Harmony for some of the most common usability errors and their solutions.
Limitations
First of all, you should have a clear idea of what happens when a user submits a form that has a JavaScript validation script:
1. The form is checked by a JavaScript like the one described below. If the script finds a mistake the submission is halted here. The user sees an alert and is asked to re-enter some data.
2. If nothing is wrong—or if JavaScript is disabled—the form is sent to the server and is processed by a CGI script.
3. If the CGI script finds a mistake it generates some HTML with an error message and sends it back to the user. In this case the user has to go back to the form, re-enter some values and again submit it.
4. If no mistakes are found, the CGI script does whatever it has to do with the data and directs the user to a Thank You page.
As you see, the form is checked for mistakes twice: by the JavaScript and by the CGI script. The CGI check always works, since CGI is server side. The JavaScript check only works when the user has JavaScript enabled. It follows that the CGI check is the most reliable: it always works regardless of what browser is used. Then why use a JavaScript check too?
The JavaScript check is very useful in addition to the CGI check because it can catch mistakes before the form is actually sent to the server. Thus the user doesn't have to use his back button to return to the form, something that may cause confusion, and then search for the incorrect form field, which may cause even more confusion. Therefore the JavaScript check is more user friendly than the CGI check.
In addition, when you use JavaScript the server doesn't need to spend quite so much time in error handling and is thus a little quicker. This only matters if you have lots and lots of forms, but it's good to keep it in mind.
So JavaScript is not a fail-safe method of catching mistakes, but it is very useful as an addition to CGI checks since it lightens the load on the server and is more user friendly. Therefore I recommend using both JavaScript form checks and CGI form checks. This way, you get both user friendliness and security.
onsubmit
When using JavaScript to check a form, the first thing you need is the onsubmit event handler. This event handler specifies a script that is executed when the user submits the form. That script is where you check whether certain fields have a value, whether the user has checked at least one checkbox, and any other checks you deem necessary.
The general syntax is:
String.Split
| <%@ Page language="c#" %> |
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// string seperated by colons ';'
string info = "mark;smith;123 csharp drive;toronto;canada";
string[] arInfo = new string[4];
// define which character is seperating fields
char[] splitter = {';'};
arInfo = info.Split(splitter);
for(int x = 0; x < arInfo.Length; x++)
{
Response.Write(arInfo[x] + "<br>");
}
}
script>
How to Delete Cookies
Deleting your browser cookies can solve many problems associated with Content Management Systems such as Plone.
Firefox 2.x
Sometimes Firefox will ask you if you want to accept a cookie. A cookie is a small amount of information that a site will save to a special file on your hard drive, then examine when you visit the site again (e.g. shopping cart information for an online business). They are usually harmless but they can present a privacy issue, since sites can use them to track what pages you visit and other personal details. They also tend to cause problems with certain Content Management Systems (CMS) like Plone, etc...
- To change your cookies preferences, go to Tools > Options (or Firefox > Preferences on a Mac).
- Click Privacy in the Category list at the top.
- Under Cookies, click Show Cookies. If you only want certain cookies removed, select a cookie and click Remove Cookie. If you want all cookies to be removed, select Remove All Cookies Now.
- When you are done changing your cookie options, click OK.
Firefox 1x
Mozilla Firefox 1.x users can delete the cookies on their hard disk drive by clicking the "Tools" menu, "Options", clicking the "Privacy" button, and under "Cookies" click the Clear button.
Internet Explorer 7.x - Windows
- Within IE, go to Tools | Internet Options.
- Click on the General tab and then click the Delete... button.
- Click the Delete cookies button.
- Click the Yes button.
- Then click the Close button, followed by the OK button.
Internet Explorer 6.x - Windows
- Within IE, go to Tools | Internet Options.
- Click Delete Cookies.
- Click OK.
Internet Explorer - Mac
- On a Classic OS machine, go to Edit | Preferences. On OS X go to Explorer | Preferences.
- Expand the Receiving Files option on the left if it isn’t already.
- Click Cookies.
- In the box that displays all the cookies on the machine, click once to select one, and then press Command-A to select all.
- Click Delete.
- Click OK.
How to Clear Your Cache
Instructions for clearing your IE and Firefox browser cache.
Internet Explorer 7.x
- Select Internet Options from the Tools pull-down menu
- Click the General tab
- On the middle of this page is the Browsing history section
- Click the Delete button
- The Delete Browsing History dialog box will display
- In the Temporary Internet Files section, click the Delete files button
- In this dialog box, you are asked - Are you sure you wish to delete all temporary Internet Explorer files?
- Click the Yes button
- On the middle of this page is the History section
- Click the Delete history button
- In this dialog box, you are asked - Are you sure you want to delete your history of visited websites?
- Click the Yes button
- Click the Close button
- Click the OK button on the General tab screen to close the Internet Options window
Internet Explorer 6.x
- Select Internet Options from the Tools pull-down menu
- Click the General tab
- On the middle of this page is the Temporary Internet Files section
- Click the Delete Files button
- You will then be prompted by the dialog box, Delete files
- In this dialog box, you are asked if you wish to Delete all files in the Temporary Internet Files folder
- Click the OK button
- On the bottom of this page is the History section
- Click the Clear History button
- You will then be prompted by the dialog box, Internet Properties
- In this dialog box, you are asked if you wish to Delete all files in your History folder
- Click the OK button
- Click the OK button on the General tab screen
Firefox 2.x
- From the main menu, select Tools, then select Options
- In the Options menu, click on the Privacy tab
- In the Private Data section, click on Settings
- The Cache box should be checked
- Click on OK
- Click on the Clear Now button
Firefox 1.5.x
- From the main menu, select Tools, then select Options
- In the Options menu, select Privacy, then select Cache
- Click Clear Cache Now
Document Actions
How to Disable Your Browser Cache
Instructions for disabling your Browser Cache. This How To refers to both Firefox and Internet Explorer 7.x and 6.x
Firefox Configuration
Each Firefox user should take a few minutes to explore the preferences that can be set in the Tools/Options dialog boxes. (You should also explore what options are available in the right-click menu that can help you over-ride your normal preferences from time-to-time.)
To disable your cache in Firefox, please follow these directions:
- In your address bar type: about:config
- In the "Filter section" type: browser.cache
- Find the browser.cache.check_doc_frequency entry
- Highlight and double click. Change the 3 (default) to 1 (which signifies "Check every time I view the page") in the dialogue box. Click OK.
- Close window, exit, and restart Firefox to enable the change.

As you can see above there's more to Firefox than what is shown in the Tools/Options menu. For more detailed information see About:config entries.
Note: It appears that Firefox preserves cache preferences across minor version upgrades. For example, in upgrading from 1.0.3 to 1.0.4, customized preferences were not reset. In addition, installing service packs and patches could restore "default" settings, bringing back cache problems you thought you had fixed!
IE Configuration
Internet Explorer 7.x
- Select Tools > Internet Options
- Under the Browsing History section select the "Settings" button
- On the "Temporary Internet files and History Settings" window make sure that under Check for newer versions of stored pages you select the radio button entitled "Every time I visit the webpage"
- Select OK
- Select OK again
- Exit IE and restart to enable the change
Internet Explorer 6.x
- Select Tools > Internet Options
- Under the Temporary Internet Files section select the "Settings" button
- On the "Settings" window make sure that under Check for newer versions of stored pages you select the radio button entitled "Every visit to the page"
- Select OK
- Select OK again
- Exit IE and restart to enable the change
How to Solve Browser Cache Issues
Information and advice for tweaking your IE and Firefox browser settings to avoid common caching problems.
Compatibility?
Internet Explorer may still be the most prevalent browser, but for compatibility with various W3C standards, Firefox and Mozilla are way ahead. IE7 may be slightly better, but seems to introduce new compatibility issues.
Advice on Caching Issues
When you visit a Web site for the first time your browser downloads all the various page elements (images, text, stylesheets etc.) to your computer's hard drive. You now have a "local cached copy" of this Web page. When you decide to visit the Web site again your browser first looks in the cache and rather than re-downloading all the page content again, it displays your "local cached copy". This approach speeds up web browsing but can be problematic, especially with certain interactive Web pages that serve up dynamic content.We have definitely seen some caching problems with Plone, the new Content Managment Software (CMS) our new Web site uses.
We highly recommend that you follow ALL of the changes suggested below. These changes may also alleviate problems you encounter with other Web sites.
First you will want to follow the instructions for disabling your cache. If you still experience problems refer to the following two documents:
If you have still have problems please let us know. Good luck!
How to: Create an ASP.NET Unit Test
You use ASP.NET unit tests to test methods that are part of ASP.NET projects. You can create an ASP.NET unit test in either of two ways:
By generating the ASP.NET unit test from an ASP.NET project. This is the most common scenario.
By configuring an existing unit test as an ASP.NET unit test.
You can also specify settings in a run configuration that correspond to the attributes used by ASP.NET unit tests. These procedures are described in the following sections.
Note: |
|---|
When you run ASP.NET unit tests, do not use the ClassCleanupAttribute or ClassInitializeAttribute attributes on any method in a class that contains an ASP.NET unit test. Similarly, do not use the AssemblyCleanupAttribute or AssemblyInitializeAttribute attributes in the same assembly as an ASP.NET unit test. The result of using these attributes in these situations is undefined. However, you can use the TestInitializeAttribute and TestCleanupAttribute attributes for any unit tests. |
Setup scripts and cleanup scripts run before and after test runs, regardless of the types of tests that are contained in those test runs. For more information about scripts that are run in conjunction with test runs, see Test Deployment Overview and How to: Specify a Test Run Configuration.
Generating an ASP.NET Unit Test To generate an ASP.NET Unit Test, you first create an ASP.NET Web site within your Visual Studio solution. You then add a class to the Web site project, and finally, generate a unit test from that class.
To generate an ASP.NET Unit Test
To generate an ASP.NET unit test, start by creating an ASP.NET Web site. To do this, right-click your solution, point to Add, and then click New Web Site.
On the Add New Web Site dialog box, click ASP.NET Web Site.
Under Location, click File System to indicate ASP.NET Development Server.
Click OK.
You now have a new Web site.
Add a class to this project. To do this, in Solution Explorer, right-click the Web site and then click Add New Item.
In the Add New Item dialog box, click Class, and then click Add.
A Microsoft Visual Studio dialog box is displayed to ask about placing the new class in the App_Code folder. Click Yes.
Note:You cannot generate tests from code in an .aspx file or in a folder other than the App_Code folder.
Generate an ASP.NET unit test. If the new class file is not already open, double-click it in Solution Explorer to open it.
Right-click the class in the class file, and then click Create Unit Tests.
The Create Unit Tests dialog box appears. For information about how to use this dialog box to generate unit tests, see How to: Generate a Unit Test.
Verify that the classes, methods, or namespaces for which you want to generate tests are selected.
(Optional) Accept the default Output project or select a new project.
When you are finished, click OK.
The new ASP.NET unit test is added to a file in your test project.
To see the unit test, open the test file and scroll to the end. The attributes that are necessary to run a unit test as an ASP.NET unit test have been automatically specified. For more information about these attributes, see the following procedure, Configuring an ASP.NET Unit Test.
Configuring an ASP.NET Unit Test You can turn an existing unit test into an ASP.NET unit test by configuring it, that is, by assigning values to certain of the test's custom attributes. You set these values in the code file that contains the unit test.
Before setting the custom attributes, you should first add a reference to the namespace that supports the custom attributes; this is the Microsoft.VisualStudio.TestTools.UnitTesting.Web namespace. With this reference in place, IntelliSense can help you set the attribute values.
Note When you generate an ASP.NET unit test, these attributes are set automatically.
To configure an ASP.NET unit test
Open the code file that contains the unit test.
Set the following attributes for the unit test:
[TestMethod]
Because all unit tests require the [TestMethod] attribute, this attribute will already be in place.
[UrlToTest()]
This is the URL that is tested when this unit test is run; for example, [UrlToTest(“http://localhost/WebSites/Default.aspx”)]
[HostType()]
Use [HostType(“ASP.NET”)]. Tests are typically run under the VSTest host process, but ASP.NET unit tests must run under the ASP.NET host process.
Examples
Example 1. If you are running your Web site with the ASP.NET Development Server, the attributes and values you set for an ASP.NET unit test might resemble the following:
[TestMethod()]
[HostType("ASP.NET")]
[UrlToTest("http://localhost:25153/WebSite1")]
[AspNetDevelopmentServerHost("D:\\Documents and Settings\\user name\\My Documents\\Visual Studio 2005\\WebSites\\WebSite1", "/WebSite1")]
Example 2. To test a Web site running under IIS, use only the attributes TestMethod, HostType, and UrlToTest:
[TestMethod()]
[HostType("ASP.NET")]
[UrlToTest("http://localhost:25153/WebSite1")]
Configuring ASP.NET Unit Tests Using Run Configuration You can specify settings in a run configuration that correspond to the attributes used by ASP.NET unit tests. After you have specified these attributes in a run configuration, the settings will apply when you run any ASP.NET unit test, whenever that run configuration is active.
Note: |
|---|
Only one set of settings for ASP.NET unit tests can be in effect: run configuration settings or attribute settings, but never a mixture of the two. Run configuration settings take precedence over attributes, if present. This means that even if you specify only one ASP.NET setting in run configuration, any ASP.NET settings specified as attributes are ignored. |
To configure ASP.NET unit tests using run configuration
Open a run configuration file. For more information, see How to: Specify a Test Run Configuration.
On the Hosts page, set the Host Type to ASP.NET.
This displays additional choices, some of which correspond to attributes you can specify in code, such as Url to Test. These attributes are described in the previous procedure, "Configuring an ASP.NET Unit Test."
When you have finished setting the values on the Hosts page, click Save and then click OK.
Trim Characters in SQL Server
How to Trim Characters in SQL Server
If you are looking for following solution than probably this post can help you out:
- How to Trim Characters in SQL Server
- How to Extract Part of String in SQL Server
- Returning only Numeric Part of String in SQL Server
- Trim String in SQL Server
- Trim Left and Right Portion of String in SQL Server
- How to Sort Numeric String in SQL Server.
I want to sort a string like this.
Nodes1-49
100-249
1000-2499
10000+
250-499
2500-4999
50-99
500-749
5000-9999
750-999
Lets go step by step and then letter sum it up.
Let find length till this “-“
select distinct MyExpr,charindex('-',MyExpr)-1 as Nodes from MyTable
| 1-49 | 1 |
| 10000+ | -1 |
| 750-999 | 3 |
| 5000-9999 | 4 |
| 250-499 | 3 |
| 1000-2499 | 4 |
| 500-749 | 3 |
| 2500-4999 | 4 |
| 100-249 | 3 |
| 50-99 | 2 |
So I also require separate statement for
select distinct MyExpr,charindex('-',MyExpr)-1 as Nodes from MyTable
| 1-49 | -1 |
| 10000+ | 5 |
| 750-999 | -1 |
| 5000-9999 | -1 |
| 250-499 | -1 |
| 1000-2499 | -1 |
| 500-749 | -1 |
| 2500-4999 | -1 |
| 100-249 | -1 |
| 50-99 | -1 |
substring(MyExpr,1,(
case
when charindex('-',MyExpr)-1 = '-1'
then charindex('+',MyExpr)-1
else charindex('-',MyExpr)-1 end
)
)
as 'NodesSort'
from MyTable
Order by 'NodesSort'
So this gives us extraction of Part of string from string. You can also see trim right portion of string.
| 1-49 | 1 |
| 100-249 | 100 |
| 1000-2499 | 1000 |
| 10000+ | 10000 |
| 250-499 | 250 |
| 2500-4999 | 2500 |
| 50-99 | 50 |
| 500-749 | 500 |
| 5000-9999 | 5000 |
| 750-999 | 750 |
Now casting the string and displaying in sorted order.
-- SORT Logic
cast(
substring(MyExpr,1,(
case
when charindex('-',MyExpr)-1 = '-1'
then charindex('+',MyExpr)-1
else charindex('-',MyExpr)-1 end
)
)
as int) as 'NodesSort'
from MyTable
order by 'NodesSort'
| 1-49 | 1 |
| 50-99 | 50 |
| 100-249 | 100 |
| 250-499 | 250 |
| 500-749 | 500 |
| 750-999 | 750 |
| 1000-2499 | 1000 |
| 2500-4999 | 2500 |
| 5000-9999 | 5000 |
| 10000+ | 10000 |