使用JavaScript检查HTML表单值是否为空

4

我希望检查一个表单是否存在空值,但是我不确定最好的方法是什么,因此我尝试了以下代码:

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>

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


当然有其他的方法,但你已经拥有了最好的方法。 - Venkata Krishna
这应该可以工作,并且如果字段为空,它不会允许提交表单。请注意,这经常会让人们感到沮丧,然后在字段中输入无意义的内容以绕过规则。当服务器接收到数据时,这将使您的数据具有非空且不感兴趣的值。从长远来看,它可能会破坏报告和其他处理。 - Lee Meador
2
既然您标记了 [tag:HTML5],那么 required 属性就会发挥作用... 此外,我建议使用 DOM 方法附加处理程序,而不是内联属性。 - Bergi
3个回答

8

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

  • 验证提交的表单中是否填写了每个 required 输入。
  • 仅在浏览器不支持 required 属性时提供 alert 行为。

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

请务必在checkform函数中添加this,不需要检查未被提交的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>

3

根据您打算支持的浏览器,您可以使用HTML5的required属性来避免使用JS。

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

Fiddle.


1

示例: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--;
 } 
}

解释:

  • 为了停止提交过程,您可以使用event.preventDefault。Event是传递给onsubmit事件函数的参数。它可以在html或addeventlistner中使用。
  • 要开始提交,必须停止prevent default的执行。
  • 您只能通过返回false来打破forEach循环。不像普通循环那样使用break;
  • 我已经放置了一个id数组,您可以在其中放置此表单将检查其是否为空的元素名称。
  • find input方法仅遍历表单元素的子元素,并查看其id是否已在id数组中提到。如果是,则将该元素添加到输入中,稍后检查是否有值在提交之前。如果没有,则调用prevent default。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接