我想检查输入值是否为空的表单,但我不确定最好的方法,所以我尝试了这个:

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>

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

最佳答案

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

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

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

    10-05 21:04
    查看更多