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