20

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?

4
  • 1
    what you want ? after the key press ? or when you click some button validate happens ? clarify Commented Feb 2, 2013 at 6:00
  • when i change the text box while entering a data "OnChange" Commented Feb 2, 2013 at 6:06
  • I'm a little unclear what you mean that the field is not getting verified the first time, but I'm guessing you mean you want to check as soon as data is entered. OnChange fires after you change the value AND lose focus on the element - if you just change the data, your event won't fire until you tab/mouseclick out of the textbox. If you want to do it on each keystroke, you should fire an event on the keyup/keydown/keypress event. Commented Feb 2, 2013 at 6:18
  • @Ravi sir, can you help me with this? Commented Feb 2, 2013 at 6:21

3 Answers 3

32

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.

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

(Or old live demo.)

Sign up to request clarification or add additional context in comments.

1 Comment

You are not covering the instance if a user just places spaces and no characters.
4

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;
    }
 }

Comments

0
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

1 Comment

It looks like you forgot to write whats your problem here. Please edit your post and provide us more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.