javascript - 表单提交javascript html中的触发操作
问题描述
如果字段验证没有错误,我正在尝试验证表单中的字段并在用户单击提交按钮时拉出不同的 html 文件。
- 但是,验证器似乎不起作用。我希望事件名称和位置字段为字母数字字符和空格,但它似乎也采用其他值。
- 将onClick="self.location='successPage.html'"放在提交按钮内似乎也不会验证字段。如果表单中的所有字段都已成功验证,我希望它移动到 successPage.html 文件。
我不想使用 jQuery。
这是我的代码:
<form action="" >
<p>
<label>
Day of the week:<br>
<select name="days">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select><br>
</label>
<label>
Start Time:<br>
<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
</label>
<label>
End Time:<br>
<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
</label>
<label>
Event Name:<br>
<input id="ename" type="text" name="ename" required /><br>
</label>
<label>
Location:<br>
<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9\s]"-->
</label>
<label>
Enter URL for the pictture:<br>
<input id="urlpic" type="text" name="urlname" />
</label>
<br><br>
<input type="reset" id="reset" value="Reset" />
<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
</p>
</form>
<script>
function chkName() {
var myName = documnet.getElementById("ename");
var pos = myName.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myName + ") again");
return false;
} else
return true;
}
function chkLoc() {
var myLoc = documnet.getElementById("loc");
var pos = myLoc.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myLoc + ") again");
return false;
} else
return true;
}
document.getElementById("ename").onchange = chkName;
document.getElementById("loc").onchange = chkLoc;
</script>
解决方案
<form action="." method="POST" onsubmit="return validate(this)">
<input type="submit" value="Submit">
</form>
form元素会在用户提交的时候传入到validate函数中,返回false表示不提交,返回true表示提交。
<script>
function validate(form) {
console.log(form); // log element to console on submit
return false; // replace with true if input is good to be submitted
}
</script>
推荐阅读
- memory-management - msync 性能是否取决于所提供范围的大小?
- react-native - Victory Native (React Native) - VictoryLine - 当 y 值超出限制时更改线条颜色
- angular - 是否有任何提示可以解决“服务命令需要在 Angular 项目中运行,但找不到项目定义”错误。
- php - 购物车中的税/价格计算混乱
- python - 在柯南中覆盖 user_info
- mocha.js - WDIO 未在密码文本换行字段中输入值[React native web]
- excel - 如何在 VBA 中使用宏获取最后记录数据
- google-cloud-ml - AutoML 训练管道作业失败。我在哪里可以找到日志?
- azure - 如何使用 Azure Powershell Runbooks 检查 Azure VM 中的 SSL 到期情况
- javascript - 将纪元时间戳转换为上午 12:01 的时间