Emptying Text Fields When Clicked Upon


if (this.value == originaldata) {   this.value = ""; } 

A nice additional feature to the preceding phrase is to clear out the text field if the user clicks into it (because then, the preselection of the text would be gone). However, just adding onclick="this.value='';" to the <input> tag would not be enough. Imagine that the user entered some custom data into the field and then decided to click in itthe text would vanish, and the user probably would too.

Therefore, the original text has to be saved upon loading of the page. Now when the user clicks in the text field and the text in it is still the original, the field may be emptied, as the following listing shows:

Clearing the Field (clear.html)

<script language="JavaScript"   type="text/javascript"> var originaldata; window.onload = function() {   var field = document.forms[0].elements["textfield"];   originaldata = field.value;   if (field.createTextRange) {     var range = field.createTextRange();     range.moveStart("character", .0);     range.moveEnd("character",       field.value.length - 1);     range.select();   } else if (field.setSelectionRange) {     field.setSelectionRange(0, field.value.length);   }   field.focus();   field.onclick = function() {     if (this.value == originaldata) {       this.value = "";     }   }; } </script> <form>   <input type="text" name="textfield"     value="&lt;Enter data here&gt;" /> </form> 

Note that the focus event cannot be used for that task; Internet Explorer would clear out the field immediately upon loading of the document (even though the call to focus() occurs before the event handler is set).

Form Validation

JavaScript is a great tool for validating forms on the fly. It is possible to give users immediate feedback about data they entered (for instance, by using something along the lines of onblur="validateData(this);"), but you have to always consider that JavaScript can be deactivated and HTTP requests must not originate from a web browser. So before you use data from the client, validate it on the server as well.

Also, make sure that the form itself works with JavaScript deactivated, since about 10% of users cannot use the scripting language (or do not want to).

Finally, validation itself should be only a convenience feature for users, not a nagging tool to squeeze as much data out of a visitor as possible. So use it wisely.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net