Validate a Text Field


No web developers want their Ajax applications to hit the network with requests if the users leave necessary text fields blank. Thus, checking that input elements of type text and the large boxes called textareas in HTML contain values is one of the most common forms of validation.
This hack shows the code for checking if a text control is blank. The inline way of doing this is by assigning a check for the field's value in the text field's event handler:
 
<input type="text" name="firstname" id="tfield" onblur=
"if (this.value) {doSomething(  );}" />

or in the textarea's event handler:
<textarea name="tarea" rows="20" id="question" cols="20" onblur=
"if (this.value) {doSomething(  );}">

The JavaScript phrase if (this.value) {...} returns false if the user leaves a field blank, so the function call doSomething( ) will never occur. JavaScript evaluates a blank web-form text field as the empty string or "", which evaluates to false when it's used in the context of a programming test. The this keyword is a nice generic way of referring to the form field that contains the event handler attribute.

Probably a better way of going about your event-handling tasks is to separate the logic of your code from the HTML or template text that comprises the application's visual aspects. The JavaScript goes into an external file that the HTML page imports with a script tag. Inside the external file, the code binds a field's various event handlers to a function or the code that represents your application's behavior.
Let's take the following web page, myapp.html, which includes the following HTML in its header:
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="js/hacks_method.js"></script>
    <title>Cool Ajax application</title>
</head>

The file hacks_method.js is located in a directory js, which is in the same directory as the HTML file. The HTML file contains the same textarea and text field as mentioned earlier, except these fields no longer have an onblur attribute. The JavaScript file includes this code:
 
window.onload=function(  ){
    var txtA = document.getElementById("tarea");
    if(txtA != null){
        txtA.onblur=function(  ){
            if (this.value) { doSomething(  );}
        };
    }
    var tfd = document.getElementById("tfield");
    /* An alternative:
    if(tfd != null && txtA != null){tfd.onblur = txtA.onblur; }
    */
    if(tfd != null){
        tfd.onblur=function(  ){
            if (this.value) { doSomething(  );}
        };
    }
}

window.onload involves the binding of the load event to your blank-field checks. load occurs when the browser has completed loading the web page, so when that happens, all the stuff after window.onload= follows.
The getElementById( ) method returns a reference to an HTML element

Related Posts:
  • Javascript For Loops JavaScript offers another type of loop, called a for loop, that’s a little more compact(and a little more confusing). For loops are usually used for repeating a series ofsteps a certain number of times, so they often involve… Read More
  • Javascript Array You can access the contents of a simple variable just by using the variable’s name.For example, alert(lastName) opens an alert box with the value stored in the variablelastName. However, because an array can hold more than o… Read More
  • Javascript While Loops A while loop repeats a chunk of code as long as a particular condition is true; in otherwords, while the condition is true. The basic structure of a while loop is this: while (condition) {// javascript to repeat} The first l… Read More
  • JavaScript Variables Variables store a value you can refer to later in the script. Variable namescan be nearly any valid identifi er. A JavaScript identifi er is a word thatcontains only letters, numbers, $, and _, and that doesn’t start with an… Read More
  • Javascript Object Type Objects are created by using the new operator followed by the name of the object type to create. Developerscreate their own objects by creating instances of the Object type and adding properties and/ormethods to it, as show… Read More
  • JavaScript System Dialogs alert(),confirm(),prompt() The browser is capable of invoking system dialogs to display to the user through the alert(),confirm(), and prompt() methods. These dialogs are not related to the web page being displayedin the browser and do not contain HTM… Read More
  • Javascript Do While Loops There’s another, less common type of loop, known as a do/while loop. This type ofloop works nearly identically to a while loop. Its basic structure looks like this: do {// javascript to repeat} while (condition) ; do {var l… Read More
  • JavaScript Alert The JavaScript alert is a dialogue box that pops up and takes the focus away from the current window and forces the web browser to read the message. 1. <form> <input type="button" onclick= "alert('Are you sure you… Read More
  • Javascript Cookies Cookies are small strings that let you store data across page views andsessions. These are some common uses of cookies:1. Keeping track of whether the user has logged in to your site2. Remembering that a user has visited a p… Read More
  • Javascript Event Object Properties Different types of events have different properties, which you’ll learn about later in the chapter. Here are a few properties common to all standard Event objects: ■ type The type of the event, like “click,” “loa… Read More
  • Javascript forEach Looping over arrays using functions is increasingly common, especially incertain libraries. Modern browsers support the forEach() method, butyou can also build your own.function arrayForEach(array, loopFunc) {// If the brows… Read More
  • Creating A Function In Javascript The basic structure of a function looks like this: function functionName() {// the JavaScript you want to run} The keyword function lets the JavaScript interpreter know you’re creating a function—it’s similar to how you use … Read More
  • HTML5 Constraint Validation API HTML5 introduces the ability for browsers to validate data in forms before submitting to theserver. This capability enables basic validation even when JavaScript is unavailable or fails to load.The browser itself handles per… Read More
  • Javascript Creating Arrays The best way to create a new array is with the array literal syntax ([]),but the array constructor function is available too. If you pass a singlenumber value to the constructor function, you get an array fi lled withthat ma… Read More
  • JavaScript String Length The length  returns the number of characters that are in a string, using an integer.<script type="text/javascript">var testString = "11111";var length = testString.length;document.write("The string length is: " + … Read More