javascript - 无法让 JS 验证响应
问题描述
我正在尝试在按下提交时进行验证,但是在按下提交时不会弹出任何警报,我应该在此处收到字段为空等的警报。任何人都可以在我的代码中发现错误吗?由于我不太了解错误是什么,因此也尝试逐行进行验证。
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["comment"].value;
if (x == "" && y == "") {
alert("Please enter the blank fields!");
return false;
} else if (x == "") {
alert("Please enter your name!");
return false;
} else if (y == "") {
alert("Please leave us a comment!");
return false;
} else {
if(document.getElementById('r5').checked) {
window.alert("Thank you")
}
}
}
.wrapper {
display: inline-block;
}
.wrapper * {
float: right;
}
.wrapper input {
display: none;
}
label {
font-size: 30px;
}
input:checked ~ label {
color: red;
}
<!doctype html>
<html>
<link REL="StyleSheet" TYPE="text/css" HREF="example2.css">
<body>
<form id ="myForm">
Name: <input type="text" id="fname">
<br><br>
Comment: <input type="input" id="comment">
<br><br>
<div class="wrapper">
<input type="radio" id="r1" name="rg1">
<label for="r1">✶</label>
<input type="radio" id="r2" name="rg1">
<label for="r2">✶</label>
<input type="radio" id="r3" name="rg1">
<label for="r3">✶</label>
<input type="radio" id="r4" name="rg1">
<label for="r4">✶</label>
<input type="radio" id="r5" name="rg1">
<label for="r5">✶</label>
</div>
<br>
<button type="button" value="Submit" onclick="validateForm"()>Submit </button>
</form>
</body>
<script src="jsreview.js"></script>
</html>
谢谢你检查这个
解决方案
首先你的不链接提交和js函数提交按钮有时会默认表单提交,所以使用按钮类型而不是提交
在函数的第一行设置alert(),方便查看
<input type=button" value= SUBMIT" onclick="validateform()" >
或者
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert( "Hello World");
}
</script>
推荐阅读
- python - mypy:“__add__”的签名与超类型“元组”不兼容 - 但 __sub__ 一切正常
- python - 如何在 Python 中根据条件更改数据的值?
- c# - 使用 XF ImagePicker 显示图像而不将图像放入资源中
- python - 如何获取长度为 n 的所有二进制数的列表?
- rust - Rust Rocket 如何推断结果/选项中包含的返回类型?
- python - 通过字符串子字符串获取唯一的字符串列表
- sql - 我可以在不知道属性名称的情况下选择 SQL 中的所有 XML 属性吗?
- pine-script - 部分平仓和止损
- http - 是否可以将(最好是空的)范围规范与空的 HTTP 实体一起使用?
- kubernetes - microk8s 安装问题“cni 插件未初始化”