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

标签 javascript html

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

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 行为。

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

请务必将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>

关于javascript - 使用 Javascript 检查 html 表单值是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640051/

相关文章:

javascript - Requirejs vs browserify vs webpack for js 加载顺序 : am I just moving the situation from one side to another?

jquery - 以 li 元素中的第二个跨度为目标

php - 按下登录按钮后,我的 login_exec 文件没有重定向

javascript - Highcharts Areaspline - 突出显示悬停效果的列

javascript - chrome事件选项卡url传递到php文件

javascript - 我可以在 WebRTC 的视频标签上渲染图像吗

javascript - AngularJS limitTo 动态扩展数组

html - 是否有必要(或建议)向 HTML 元素添加 CSS 样式?

javascript - 在第二个 HTML 页面上显示 JavaScript 函数的结果

jquery - 如何将一系列嵌套列表变成米勒列?