Checking if a textbox is empty in Javascript

前端 未结 3 1293
孤街浪徒
孤街浪徒 2020-12-08 11:26

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         


        
相关标签:
3条回答
  • 2020-12-08 11:55

    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;
        }
     }
    
    0 讨论(0)
  • 2020-12-08 11:58
    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

    0 讨论(0)
  • 2020-12-08 12:10

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

    0 讨论(0)
提交回复
热议问题