javascript - 为什么验证不适用于提供的 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学习的新手。
解决方案
几个问题
- 中的拼写错误
document.getElementById
- 另一方面缺少文件
document.getElementById
- 没有 preventDefault 如果有任何 JS 错误将提交表单
- = 是赋值 - 你需要 == 或 === 来比较
- 跨度需要在选择之外
- 您没有在“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>
推荐阅读
- reactjs - 如何将道具(从 Redux 获取)从一个组件传递到另一个组件(React/Redux)?
- c++ - 有没有办法在 boost::promise 已经设置时捕获从 boost::promise 抛出的异常?
- python - 从特定行中选择特定列(Python - MySQL)
- mongoose - 常数未反映在函数中
- php - 使用 JQuery 启用和禁用下拉列表的问题
- android - 如何设置RecyclerView的长度不超过屏幕
- node.js - 带有多个 MongoDB 查询的 Express 中的异步/等待
- android - 如何防止用户数据再次输入 firebase 数据库?
- c - 我在这个片段中使用 malloc 错误吗
- c++ - 为什么这种算法的“改进”不起作用?