首页 > 解决方案 > 为什么验证不适用于提供的 html/js 代码

问题描述

如果没有选择,我希望在 html 页面中获得所需的内容。

function validation() {
  var country = getElementById("country");
  if (country.value = "") {
    documnet.getElementById("countryy").innerHTML = "Required";
    return false;
  } else
    return true;
}
<form onsubmit="return validation();">

  <select id="country"><span id="countryy"></span>

  </select><br>

  <input type="submit" name="Submit" value="Submit">
</form>

为什么验证不适用于提供的 html/js 代码。如果没有选择,我希望在 html 页面中获得所需的内容。我是js学习的新手。

标签: javascripthtml

解决方案


几个问题

  1. 中的拼写错误document.getElementById
  2. 另一方面缺少文件document.getElementById
  3. 没有 preventDefault 如果有任何 JS 错误将提交表单
  4. = 是赋值 - 你需要 == 或 === 来比较
  5. 跨度需要在选择之外
  6. 您没有在“NONE”选项中使用 value="Default"

不建议使用内联事件处理程序。这里有更好的版本

注意我添加了一个类来切换所需的,以防用户更改选择以符合

window.addEventListener("load", function() {
  const errorSpan = document.getElementById("countryy"); // cache the elements
  const country = document.getElementById("country");
  document.getElementById("myForm").addEventListener("submit", function(e) {
    const val = country.value; // get the value
    if (val === "") {
      e.preventDefault(); // stop submit
    }
    errorSpan.classList.toggle("hide",val); // hide if value
  })
  country.addEventListener("change",function() { // if user changes the select
    errorSpan.classList.toggle("hide",this.val); // hide if value
  })
})
.hide { display : none; }
<form id="myForm">
  <select id="country">
    <option value="">NONE</option>
    <option value="ABDUL">ABDUL</option>
    <option value="SULE">SULE</option>
  </select> <span id="countryy" class="hide">Required</span><br>
  <input type="submit" name="Submit" value="Submit">
</form>

但是,您可以删除所有脚本,只需将required属性添加到选择并保留空默认值

<form id="myForm">
  <select id="country" required>
    <option value="">NONE</option>
    <option value="ABDUL">ABDUL</option>
    <option value="SULE">SULE</option>
  </select><span id="countryy"></span><br>
  <input type="submit" name="Submit" value="Submit">
</form>


推荐阅读