Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
309 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...