Hi!

I have written this function in javascript.
The problem I'm facing is that even when the text field in html form is empty, this function behaves as alert("");. It must display "Enter some text" in alert box. The function, however, works well when I enter "Hello" in the text field and alert displays "Hello"

function interpret()
{
    var a=null;
    a=document.forms["input"]["box"].value;

    if(a==null)
    {
        alert("Enter some text");
        return false;
    }
    else
    {
        alert(a);
        return true;
    }
}

What is the problem here. Pleas help me out.

Try it just by making null a string

if('null' == a)

Or try this :

   a=document.forms["input"]["box"].value;

   if( trim( a ) != '' )
        alert( a );
    else
        alert( 'Enter some text' );

    // Function to trim the space in the  string
    function trim( s ) {
       var temp = s;
       return temp.replace(/^\s+/,'').replace(/\s+$/,'');
    }

Here are a couple of other useful trimming functions :

// Function to trim the space in the left side of the string
function ltrim( s ) {
  return s.replace( /^\s*/, "" );
}

// Function to trim the space in the right side of the string
function rtrim( s ) {
   return s.replace( /\s*$/, "" );
}

you can simplify this

function interpret(){ var a=null; a=document.forms["input"]["box"].value; if(a==null) { alert("Enter some text"); return false; } else { alert(a); return true; }}

with

function interpret(a){
    a=document.forms['input']['box'].value;
    if(+a==0)
        alert('enter some text');
        else alert(a);
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.