Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Thursday, July 15, 2010

Form


Introduction to Forms

On this page I give the code you need for checking user input in a form. Using these bits of code, you can write your own scripts to validate 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 fewmethods and properties of the form itself. Then it's time for accessing the form elements and the specific syntax for accessing the user definedvalue 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 bothJavaScript 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 theonsubmit 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:

where checkscript() 
is the name of the script. This script should return either true or false.
 If false is returned, the form will not be submitted. If either true or false is returned the script stops.
So the general script becomes something like:
function checkscript() { 	if (some value is/is not something) { 		// something is wrong 		alert('alert user of problem'); 		return false; 	} 	else if (another value is/is not something) { 		// something else is wrong 		alert('alert user of problem'); 		return false; 	}  	// If the script makes it to here, everything is OK, 	// so you can submit the form  	return true; } 

Of course this function can become much more complex if you have to check a complicated form with a lot of radio buttons and things. The general idea remains the same, however: You go through the elements, check whatever you want to check and as soon as you find any mistake, you return false, after which the script stops and the form is not submitted.

Once you've found a mistake, you should notify the user of the problem. This used to be done by an alert, but nowadays you can generate error messages and insert them next to the form field.

Only at the very end of the script, when you have checked all elements and encountered no mistakes, you return true, after which the form is submitted.

Form methods and properties

JavaScript has a few built-in methods and properties for dealing with forms. Three of them are especially important:

You can submit a form by using the submit() method. To submit the first form on the page, do

document.forms[0].submit() 

Please note that when a form is submitted by JavaScript the onsubmitevent handler is never executed.
To reset the form, do

document.forms[0].reset() 

I assume, but have not tested, that the onreset event handler isn’t executed either if you reset the form through JavaScript.

Finally, you can change the ACTION of a form if you want to:

document.forms[0].action = 'the_other_script.pl'; 

This can come in very handily if a form has to be submitted to another script in some cases.

Accessing the form elements

The form validation script needs to access the form in the HTML page to determine what values the user has filled in. So first we have to enter the form by means of the Level 0 DOM. The general syntax for accessing a form element is:

document.forms[number].elements[number] 

When the page is loaded, JavaScript makes an array forms in which it puts all the forms that are on the page. The first form is forms[0], the second is forms[1] etc.

Each form has another array in which JavaScript puts all the elements in the form. The first elements is elements[0], the second elements[1] etc. Every , and is an element.

In some cases, it's better to use the names of the forms and elements. In HTML, you have to give a name to each form and each element, like:

     

Now you can access these elements by:

document.personal.name document.personal.address document.personal.city 

The advantage of using names is that you can put all elements somewhere else in the page and still have a working script, while a script using numbers will have to be changed. After all, the input box city isdocument.forms[0].elements[2] in the example above, but when you suddenly put it at the top of the form, it becomesdocument.forms[0].elements[0] and you have to change the script.

Determining values

Of course, the most important thing is to find out what the user has filled in or checked in the form. At other times you might want to fill in something in the form.

Below are snippets of scripts that help you access form elements. All of them are meant to send the user input to the variable user_input. After you've done that, you can check this value for whatever you want.

If you'd like to study a practical example, see the example form and script.

Texts, textareas and hidden fields

Very simple:

user_input = document.forms[0].text.value 

where text is the name of the text field, textarea or hidden field. Thevalue of this element gives the text, so we transfer it to user_input.

Writing is also possible:

document.forms[0].text.value = 'The new value'; 

Select boxes

Select boxes are simple too:

user_input = document.forms[0].select.value; 

To change the selected option in a select box, you have to change itsselectedIndex, like

document.forms[0].select.selectedIndex = 2; 

Now the third option in the box is selected.

Old browsers

In old browsers, select boxes didn't yet have a value property. Back then, this was the way to find the value of a select box:

var selectBox = document.forms[0].select; user_input = selectBox.options[selectBox.selectedIndex].value 

First, we need to find out which option the user has selected.document.forms[0].select.selectedIndex gives us the number of the selected option. JavaScript has created an array options which contains all options of the select box. So we ask for the selected option in this array and take the value of it, which we transfer to user_input.

Checkboxes

Checkboxes need a slightly different approach. We already know their values, but want to know whether the user has checked them. Thechecked property tells us. It can have two values: true or false.

Now we do:

if (document.forms[0].checkbox.checked) { 	user_input = document.forms[0].checkbox.name } 

in which checkbox is the name of the checkbox. If the checkbox ischecked, we take its name (or its value, if you need that bit of data) and transfer it to user_input.

To check a checkbox, set its property checked to true:

document.forms[0].checkbox.checked = true 

Radio buttons

Unfortunately it's not possible to see at once which radio button in a group the user has checked. You need to go through all radio's and see which one's checked property is true.

for (i=0;i

where radios is the name of the group of radio buttons.

Note that document.forms[0].radios is an array filled with all radio buttons. Loop through all of them and see if it is checked. If one is, transfer the value of that radio button to user_input.

document.forms[0].radios.length gives the number of radio buttons. For each radio button, we see if it is

To check a radio button, set its property checked to true:

document.forms[0].radios[i].checked = true;

Monday, July 12, 2010

PARSING A LARGE JSON FILE EFFICIENTLY AND EASILY

When parsing a JSON file, or an XML file for that matter, you have two options. You can read the file entirely in an in-memory data structure (a tree model), which allows for easy random access to all the data. Or you can process the file in a streaming manner. In this case, either the parser can be in control by pushing out events (as is the case with XML SAX parsers) or the application can pull the events from the parser. The first has the advantage that it is easy to chain multiple processors but it is quite hard to implement, the second has the advantage that it is rather easy to program and that you can stop parsing when you have what you need.

Recently I was working on a little import tool for Lily, which would read a schema description and records from a JSON file and put them into Lily.

Since I did not want to spent hours on this, I thought it was best to go for the tree model, thus reading the entire JSON file into memory. Still, it seemed like the sort of tool which might be easily abused: generate a large JSON file, then use the tool to import it into Lily. In this case, reading the file entirely into memory might be impossible.

So I started using Jackson's pull API, but quickly changed my mind as this would be too much work. But then I looked a bit closer at Jackson's API and found out that it is very easy to combine the streaming and tree-model parsing options: you can move through the file as a whole in a streaming way, and then read individual objects into a tree structure.

As an example, let's take the following input:

{    "records": [      {"field1": "outer", "field2": "thought"},      {"field2": "thought", "field1": "outer"}    ] ,   "special message": "hello, world!"  }

For this simple example it would be better to use plain CSV, but just imagine the fields being sparse or the records having a more complex structure.

The following snippet illustrates how this file can be read using a combination of stream and tree-model parsing. Each individual record is read in a tree structure, but the file is never read in its entirety into memory, making it possible to process JSON files gigabytes in size while using minimal memory.

import org.codehaus.jackson.map.*; import org.codehaus.jackson.*;  import java.io.File;  public class ParseJsonSample {   public static void main(String[] args) throws Exception {     JsonFactory f = new MappingJsonFactory();     JsonParser jp = f.createJsonParser(new File(args[0]));      JsonToken current;      current = jp.nextToken();     if (current != JsonToken.START_OBJECT) {       System.out.println("Error: root should be object: quiting.");       return;     }      while (jp.nextToken() != JsonToken.END_OBJECT) {       String fieldName = jp.getCurrentName();       // move from field name to field value       current = jp.nextToken();       if (fieldName.equals("records")) {         if (current == JsonToken.START_ARRAY) {           // For each of the records in the array           while (jp.nextToken() != JsonToken.END_ARRAY) {             // read the record into a tree model,             // this moves the parsing position to the end of it             JsonNode node = jp.readValueAsTree();             // And now we have random access to everything in the object             System.out.println("field1: " + node.get("field1").getValueAsText());             System.out.println("field2: " + node.get("field2").getValueAsText());           }         } else {           System.out.println("Error: records should be an array: skipping.");           jp.skipChildren();         }       } else {         System.out.println("Unprocessed property: " + fieldName);         jp.skipChildren();       }     }                   } }

As you can guess, the nextToken() call each time gives the next parsing event: start object, start field, start array, start object, ..., end object, ..., end array, ...

The jp.readValueAsTree() call allows to read what is at the current parsing position, a JSON object or array, into Jackson's generic JSON tree model. Once you have this, you can access the data randomly, regardless of the order in which things appear in the file (in the example field1 and field2 are not always in the same order). Jackson supports mapping onto your own Java objects too. The jp.skipChildren() is convenient: it allows to skip over a complete object tree or an array without having to run yourself over all the events contained in it.

Once again, this illustrates the great value there is in the open source libraries out there.

Thursday, July 8, 2010

24 JavaScript Best Practices for Beginners

24 JavaScript Best Practices for Beginners
basix

24 JavaScript Best Practices for Beginners

As a follow-up to “30 HTML and CSS Best Practices”, this week, we’ll review JavaScript! Once you’ve reviewed the list, be sure to let us know what little tips you’ve come across!


1. Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

“If two operands are of the same type and value, then === produces true and !== produces false.” – JavaScript: The Good Parts

However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.


2. Eval = Bad

For those unfamiliar, the “eval” function gives us access to JavaScript’s compiler. Essentially, we can execute a string’s result by passing it as a parameter of “eval”.

Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!


3. Don’t Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:

  1. if(someVariableExists)
  2. x = false

However, consider this:

  1. if(someVariableExists)
  2. x = false
  3. anotherFunctionCall();

One might think that the code above would be equivalent to:

  1. if(someVariableExists) {
  2. x = false;
  3. anotherFunctionCall();
  4. }

Unfortunately, he’d be wrong. In reality, it means:

  1. if(someVariableExists) {
  2. x = false;
  3. }
  4. anotherFunctionCall();

As you’ll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

  1. if(2 + 2 === 4) return 'nicely done';

Always Consider the Future

What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line – tread with caution when omitting.


4. Utilize JS Lint

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

“JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
– JSLint Documentation

Before signing off on a script, run it through JSLint just to be sure that you haven’t made any mindless mistakes.



5. Place Scripts at the Bottom of Your Page

This tip has already been recommended in the previous article in this series. As it’s highly appropriate though, I’ll paste in the information.

Place JS at bottom

Remember — the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can’t continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.

If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.

Better

  1. <p>And now you know my favorite kinds of corn. p>
  2. <script type="text/javascript" src="path/to/file.js">script>
  3. <script type="text/javascript" src="path/to/anotherFile.js">script>
  4. body>
  5. html>

6. Declare Variables Outside of the For Statement

When executing lengthy “for” statements, don’t make the engine work any harder than it must. For example:

Bad

  1. for(var i = 0; i <>
  2. var container = document.getElementById('container');
  3. container.innerHtml += 'my number: ' + i;
  4. console.log(i);
  5. }

Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!

Better

  1. var container = document.getElementById('container');
  2. for(var i = 0, len = someArray.length; i <>
  3. container.innerHtml += 'my number: ' + i;
  4. console.log(i);
  5. }

Bonus points to the person who leaves a comment showing us how we can further improve the code block above.


7. The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

  1. var arr = ['item 1', 'item 2', 'item 3', ...];
  2. var list = '
    • ' + arr.join('
    • ') + '
    '
    ;

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!

Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
- James Padolsey, james.padolsey.com


8. Reduce Globals

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries."
- Douglas Crockford

  1. var name = 'Jeffrey';
  2. var lastName = 'Way';
  3. function doSomething() {...}
  4. console.log(name); // Jeffrey -- or window.name

Better

  1. var DudeNameSpace = {
  2. name : 'Jeffrey',
  3. lastName : 'Way',
  4. doSomething : function() {...}
  5. }
  6. console.log(DudeNameSpace.name); // Jeffrey

Notice how we've "reduced our footprint" to just the ridiculously named "DudeNameSpace" object.


9. Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

  1. // Cycle through array and echo out each name.
  2. for(var i = 0, len = array.length; i <>
  3. console.log(array[i]);
  4. }

10. Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!

11. Don't Pass a String to "SetInterval" or "SetTimeOut"

Consider the following code:

  1. setInterval(
  2. "document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
  3. );

Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.

  1. setInterval(someFunction, 3000);

12. Don't Use the "With" Statement

At first glance, "With" statements seem like a smart idea. The basic concept is that they can be used to provide a shorthand for accessing deeply nested objects. For example...

  1. with (being.person.man.bodyparts) {
  2. arms = true;
  3. legs = true;
  4. }

-- instead of --

  1. being.person.man.bodyparts.arms = true;
  2. being.person.man.bodyparts.legs= true;

Unfortunately, after some testing, it was found that they "behave very badly when setting new members." Instead, you should use var.

  1. var o = being.person.man.bodyparts;
  2. o.arms = true;
  3. o.legs = true;

13. Use {} Instead of New Object()

There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:

  1. var o = new Object();
  2. o.name = 'Jeffrey';
  3. o.lastName = 'Way';
  4. o.someFunction = function() {
  5. console.log(this.name);
  6. }

However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.

Better

  1. var o = {
  2. name: 'Jeffrey',
  3. lastName = 'Way',
  4. someFunction : function() {
  5. console.log(this.name);
  6. }
  7. };

Note that if you simply want to create an empty object, {} will do the trick.

"Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc." - dyn-web.com


14. Use [] Instead of New Array()

The same applies for creating a new array.

Okay

  1. var a = new Array();
  2. a[0] = "Joe";
  3. a[1] = 'Plumber';

Better

  1. var a = ['Joe','Plumber'];

"A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object." - Douglas Crockford


15. Long List of Variables? Omit the "Var" Keyword and Use Commas Instead

  1. var someItem = 'some string';
  2. var anotherItem = 'another string';
  3. var oneMoreItem = 'one more string';

Better

  1. var someItem = 'some string',
  2. anotherItem = 'another string',
  3. oneMoreItem = 'one more string';

...Should be rather self-explanatory. I doubt there's any real speed improvements here, but it cleans up your code a bit.


17. Always, Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

  1. var someItem = 'some string'
  2. function doSomething() {
  3. return 'something'
  4. }

Having said that, this is a very bad practice that can potentially lead to much bigger, and harder to find, issues.

Better

  1. var someItem = 'some string';
  2. function doSomething() {
  3. return 'something';
  4. }

18. "For in" Statements

When looping through items in an object, you might find that you'll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information

  1. for(key in object) {
  2. if(object.hasOwnProperty(key) {
  3. ...then do something...
  4. }
  5. }

As referenced from JavaScript: The Good Parts, by Douglas Crockford.


19. Use Firebug's "Timer" Feature to Optimize Your Code

Need a quick and easy way to determine how long an operation takes? Use Firebug's "timer" feature to log the results.

  1. function TimeTracker(){
  2. console.time("MyTimer");
  3. for(x=5000; x > 0; x--){}
  4. console.timeEnd("MyTimer");
  5. }

20. Read, Read, Read...

While I'm a huge fan of web development blogs (like this one!), there really isn't a substitute for a book when grabbing some lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here are some of my JavaScript favorites.

Read them...multiple times. I still do!


21. Self-Executing Functions

Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

  1. (function doSomething() {
  2. return {
  3. name: 'jeff',
  4. lastName: 'way'
  5. };
  6. })();

22. Raw JavaScript Can Always Be Quicker Than Using a Library

JavaScript libraries, such as jQuery and Mootools, can save you an enormous amount of time when coding -- especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly).

jQuery's "each" method is great for looping, but using a native "for" statement will always be an ounce quicker.


23. Crockford's JSON.Parse

Although JavaScript 2 should have a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser that you can use. It can be downloaded HERE.

Simply by importing the script, you'll gain access to a new JSON global object, which can then be used to parse your .json file.

  1. var response = JSON.parse(xhr.responseText);
  2. var container = document.getElementById('container');
  3. for(var i = 0, len = response.length; i <>
  4. container.innerHTML += '
  5. ' + response[i].name + ' : ' + response[i].email + '
  6. ';
  7. }

24. Remove "Language"

Years ago, it wasn't uncommon to find the "language" attribute within script tags.

However, this attribute has long since been deprecated; so leave it out.