admin管理员组

文章数量:1289944

Can anyone please tell me what the problem is with this code:

function c(id)
{
    var empty = document.getElementById(id);
    if(empty.length<1)
    {
        window.alert ("This field cant be left empty");
        return true;
    }
    else
    {
        return false;
    }

}

This is my html code:

<textarea rows="3" cols="80" id="ta1" onChange="c('ta1');"></textarea>

Can anyone please tell me what the problem is with this code:

function c(id)
{
    var empty = document.getElementById(id);
    if(empty.length<1)
    {
        window.alert ("This field cant be left empty");
        return true;
    }
    else
    {
        return false;
    }

}

This is my html code:

<textarea rows="3" cols="80" id="ta1" onChange="c('ta1');"></textarea>
Share Improve this question edited Jan 22, 2013 at 10:05 Jeroen 63.8k46 gold badges228 silver badges366 bronze badges asked Jan 22, 2013 at 9:55 suhassuhas 1273 gold badges3 silver badges11 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 5

The value property of the textarea should be checked to determine if it is empty.

   var content = document.getElementById(id).value;

   if(content.length<1)
   {
        window.alert ("This field cant be left empty");
        return true;
   }
   else
   {
        return false;
   }

Working Example: http://jsfiddle/35DFR/2/

Try this:

function c(id)
{
    if(document.getElementById(id).value == '')
    {
        window.alert ("This field cant be left empty");
        return true;
    }
    else
    {
        return false;
    }

}

If you want to go a bit further, you might want to trim the value first though.

Update:

From the ments, try changing the 'onchange' to 'onkeyup':

<textarea rows="3" cols="80" id="ta1" onkeyup="c('ta1');"></textarea>
if (YOURFORM.YOURTEXTFIELDVARIABLENAME.value == "")

{
     return True

}
function c(id) {
    var empty =document.getElementById(id);
    if(!empty.value){
        window.alert("This field cant be left empty");
        return true;
    }else{
        return false;
    }
}

try this

本文标签: javascriptcheck whether a textarea is emptyStack Overflow