spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / forms 12
[next]
Biz Resources
ERP Software
Computer Hardware
Data Backup Services
Developer News
SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear

JavaScript and Forms

by Mark Young (mark.young@educk.co.nz)

Have you ever wished to be able to create a small application on your Web site that would interact with the viewer, or wished to make sure that form input actually contained something worthwhile rather than just being a blank waste of space after someone just hit submit? Well, JavaScript, combined with a little DHTML can provide a solution to these problems, and introduce many great cool features to add an extra little "something" to your site.

In this article I'll show how to use JavaScript to access forms, how to manipulate data, and finally how to create a couple of small applications to show how its done. This is not meant to be a JavaScript tutorial, it assumes you have a basic understanding of JavaScript. Extensive knowledge is not necessary.

Accessing the form

The first step in being able to use user input is to access this input. Lets create a simple form: <form name="formone" onsubmit="showData()" action=">; <input name="inputone" type="text"> <input type="submit" value="Show"> </form> Notice that I have named all these elements - it makes it much easier for accessing. Now for the JavaScript. Put this in your tag. <script language="JavaScript"> <!-- function showData() { alert(document.formone.inputone.value); } //--> </script> This will display the text when the button is pressed. Thankfully this DOM works both in Netscape and IE. Notice I have called it by the form name, then the input name. This could quite easily be accomplished by using document.forms[0].elements[0].value, but this is more complicated, and harder to keep track of when pasting from one document into another. As a rule, use the names.

Using What You've Accessed

Now that you've accessed the data, you'll want to be able to do something with it. Some of the simplest things are called validations - or making sure that the user entered what you wanted them to enter.

Making sure they entered numbers

There are many ways to do this, but here is one of the simplest. Change the string to an integer, and see if the length is still the same - if it is, then the input is a number, otherwise there's some funny characters in there. Here's our new script - replace the old one with this one:

<script language="Javascript"> function showData() { var oldstring = document.formone.inputone.value; var newstring = parseFloat(oldstring).toString(); var InpValid=1; if (oldstring.length == newstring.length &amp;&amp; newstring != "NaN") { alert("Input is a number"); } else { alert("Input is not a number"); InpValid=0; } } </script> Don't worry about "InpValid" for the moment - it comes up later on.

I've converted the second string to a floating point integer, and then back to a string - this eliminates all the non-numeric characters. To check for an actual integer (i.e. whole numbers only) just substitute parseInt for parseFloat. Note the code to check for "NaN." Without this, three letter inputs would return as numbers. You can also use this to check that the user has entered in a certain number of digits - just include "&& newstring.length == 5" or whatever length you desire to the if statement. This is useful is say a ZIP number is needed.

Making sure they've entered a valid email address:

This is one thing that isn't fool-proof in any sense of the word - but it does stop people from entering "myemail" or some rubbish in the box - and hopefully, if they do this, they will get a fright and actually put in their real e-mail address. There are longer ways of validating e-mails, like searching for valid characters, but this is a simple solution that works on a basic level - I'll leave you to extend this code.

What I'm going to do here is to search the input for the character "@" which all e-mail addresses have in them - and make sure it is not next to a space, or the end or beginning of the line. Of course you can still enter in silly e-mail addresses, but at least it forces the user to enter something resembling an e-mail address.

We're going to have to use the regExp object and the search command - for more information see http://www.webreference.com/js/column5/regular.html.

var InpTwo = document.formone.inputtwo.value; var newreg = /@\b/gi; //set up search parameters if (InpTwo.match(newreg)) { //see if found newarray=InpTwo.match(newreg); if (newarray.length == 1) { alert("Valid email address entered"); } else { alert("Not a valid e-mail address"); InpValid=0; } } else { alert("Not a valid e-mail address"); InpValid=0; } As you can see, I've added a new input box to my form and called it "inputtwo," but you can change this, or just reuse the previous one.

The final thing to do is to actually submit your form. Add this code to the end of the function:

if(InpValid=1) { document.formone.action="mailto:youraddress@wherever.com"; } The check for InpValid ensures that the form is not submitted if there were mistakes in it.
Note that this action is whatever you would normally have as the action="" in the form.
Enter a Number: Enter your Email:

home / programming / javascript / forms 12
[next]




JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Software Engineering for Ajax · Perl Pragma Primer · Implement Drag and Drop in Your Web Apps: Part 2
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Policy-based Management in SQL Server 2008 – Part II · For Starters: Virtualization - Part 1 · USPS Rate-Change Tips for E-tailers

Created: January 26, 2001
Revised: January 26, 2001
URL: http://www.webreference.com/programming/javascript/forms