[javascript] Checking if a textbox is empty in Javascript

This is my code which was supposed to raise an alert message if the textbox is left empty:

function a(id)
{
    var n=document.getElementById(id).value;
    if (n.length < 1)
    {
        window.alert("Field is blank");
        return false;
    }
}

The bug I'm getting is that the field is not getting verified onChange the first time. But when the text box is filled with some data and erased, now the OnChange fires, and the alert message is displayed. How can I fix this bug?

This question is related to javascript html

The answer is


onchange will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.

So it is better to use onblur event or on submitting the form.

_x000D_
_x000D_
function checkTextField(field) {_x000D_
  document.getElementById("error").innerText =_x000D_
    (field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
_x000D_
_x000D_

(Or old live demo.)


your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

function valid(id)
    {
        var textVal=document.getElementById(id).value;
        if (!textVal.match("Tryit") 
        {
            alert("Field says Tryit");
            return false;
        } 
        else 
        {
            return true;
        }
     }

Use this for expressing things