Html 使用Javascript检查html表单值是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18640051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:05:04  来源:igfitidea点击:

Check if html form values are empty using Javascript

javascripthtml

提问by vicR

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:

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:

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?

有人有想法或更好的解决方案吗?

回答by lightswitch05

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

添加required属性是现代浏览器的好方法。但是,您很可能还需要支持旧版浏览器。这个 JavaScript 将:

  • Validate that every requiredinput (within the form being submitted) is filled out.
  • Only provide the alertbehavior if the browser doesn't already support the requiredattribute.
  • 验证required是否填写了每个输入(在提交的表单内)。
  • alert当浏览器不支持该required属性时才提供行为。

JavaScript :

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 thisto the checkform function, no need to check inputsthat are not being submitted.

一定要添加this到checkform函数中,不需要检查inputs没有提交。

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

回答by pdoherty926

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

根据您计划支持的浏览器,您可以使用 HTML5 required 属性并放弃 JS。

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

Fiddle.

小提琴。

回答by Muhammad Umer

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

演示: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.
  • 要停止提交过程,请使用 event.preventDefault。事件是传递给函数 onsubmit 事件的参数。它可以是 html 或 addeventlistner。
  • 要开始提交,您必须停止阻止默认执行​​。
  • 您可以仅通过重新调整 false 来中断 forEach 循环。不使用中断;与普通循环一样..
  • 我已经把 id 数组放在那里你可以把这个论坛会检查它们是否为空的元素的名称。
  • find 输入法只是遍历表单元素的子元素,看看它们的 id 是否已经在 id 数组中被提及。如果是,则将该元素添加到输入中,稍后在提交之前检查其中是否有值。如果没有它调用防止默认。