Checking if a textbox is empty in Javascript

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.)

Leave a Comment