最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Check if html form values are empty using Javascript - Stack Overflow

programmeradmin1浏览0评论

I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:

Javascript:

  function checkform()
    {
      if (document.getElementById("promotioncode").value == "")
    {
        // something is wrong
        alert('There is a problem with the first field');
        return false;
    }

    return true;
    }

html:

  <form id="orderForm" onSubmit="return checkform()">
      <input name="promotioncode" id="promotioncode" type="text" />
      <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/>
      <input class="submit" type="submit" value="Submit"/>
  </form>

Does anybody have an idea or a better solution?

I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:

Javascript:

  function checkform()
    {
      if (document.getElementById("promotioncode").value == "")
    {
        // something is wrong
        alert('There is a problem with the first field');
        return false;
    }

    return true;
    }

html:

  <form id="orderForm" onSubmit="return checkform()">
      <input name="promotioncode" id="promotioncode" type="text" />
      <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/>
      <input class="submit" type="submit" value="Submit"/>
  </form>

Does anybody have an idea or a better solution?

Share Improve this question edited Jan 29, 2019 at 19:40 nickhar 20.9k12 gold badges63 silver badges77 bronze badges asked Sep 5, 2013 at 15:13 vicRvicR 8194 gold badges24 silver badges53 bronze badges 3
  • There are other ways to do it obviously but you already have the best way – Venkata Krishna Commented Sep 5, 2013 at 15:16
  • That should work and won't let the form be submitted if the field is blank. Note that this often frustrates people who then type gibberish in the field to get around the rule. That leaves you with a non-blank, non-interesting value in your data when the server gets it. It can mess up reports and other processing in the long run. – Lee Meador Commented Sep 5, 2013 at 15:18
  • 2 Since you tagged this html5, the required attribute should do it… Apart from that I would suggest attaching handlers with DOM methods instead of inline attributes. – Bergi Commented Sep 5, 2013 at 15:21
Add a comment  | 

3 Answers 3

Reset to default 8

Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:

  • Validate that every required input (within the form being submitted) is filled out.
  • Only provide the alert behavior if the browser doesn't already support the required attribute.

JavaScript :

function checkform(form) {
    // get all the inputs within the submitted form
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        // only validate the inputs that have the required attribute
        if(inputs[i].hasAttribute("required")){
            if(inputs[i].value == ""){
                // found an empty field that is required
                alert("Please fill all required fields");
                return false;
            }
        }
    }
    return true;
}

Be sure to add this to the checkform function, no need to check inputs that are not being submitted.

<form id="orderForm" onsubmit="return checkform(this)">
    <input name="promotioncode" id="promotioncode" type="text" required />
    <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/>
    <input class="submit" type="submit" value="Submit"/>
</form>

Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.

<input name="promotioncode" id="promotioncode" type="text" required />

Fiddle.

Demo: http://jsfiddle.net/techsin/tnJ7H/4/#

var form = document.getElementById('orderForm'),
    inputs=[], ids= ['price','promotioncode'];


//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
   var c=true;
   inputs.forEach(function(e){ if(!e.value) {c=false;  return c;}  });
   if(!c)  e.preventDefault();
};


//findInputs function
function fi(x){
 var f = x.children,l=f.length;
 while (l) {
    ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
    l--;
 } 
}

Explanation:

  • To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
  • To begin submit you have to stop prevent default from executing.
  • You can break forEach loop by retuning false only. Not using break; as with normal loops..
  • i have put id array where you can put names of elements that this forum would check if they are empty or not.
  • find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.
发布评论

评论列表(0)

  1. 暂无评论