0

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.

4
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Troy III
0

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*$/, "" );
}
0

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);
};
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.