阻止input type是submit的提交和跳转(button 写onclick函数失败后的反思)
button写onclick函数不能提交
本人小白,写给笨笨的自己。
之前从来没写过,但是也感觉每次写代码都有绕很多弯路,还是记下来方便自己吧。其实是之前太懒了 (希望能同时方便其他人?不过大家都比我强就是了。)
在做数据库作业时前端提交网页想写一个验证码提交,也就是需要如下的代码:
在jsp中的form标签的id是“form1”
在jsp中的input标签
<input type="button" style="width:200px;height:50px;" value="Login" name="button1" id="button11" onclick="checkYOrN()"/>
checkYOrN()函数:
function checkYOrN(){
var val=document.getElementById("Code").value;
var num = rd_code.join("");
if(val==''){
alert('Error!');
}else if(val == num){
document.getElementById(".input-val").val('');
draw(rd_code);
var form1 = document.getElementById("form1");
form1.submit();
}else{
alert('Error!');
document.getElementById("text").value='';
draw(rd_code);
}
看了很多篇博客也没找出是自己哪有问题……还是俺太菜。
于是放弃,转换思路。
利用input submit按钮实现
看网上大家都说在input button的时候很容易写成submit造成混淆,俺寻思着要不写个submit试试。
这里借鉴了大神的思路:
https://blog.csdn.net/qiutaixin/article/details/78970069
所以解决方案就是把原来的form标签
<form action="<%=request.getContextPath() %>/Login" method="post" id="form1" >
改成
<form action="<%=request.getContextPath() %>/Login" method="post" id="form1" onsubmit="return checkYOrN()">
再更改checkYOrN()函数的返回值:
return true: 跳转
return false: 不跳转,但提交。不过我这里提交了也不会怎么样,不会发生安全性问题。
function checkYOrN(){
var val=document.getElementById("Code").value;
var num = rd_code.join("");
if(val==''){
alert('Error!');
return false;
}else if(val == num){
document.getElementById(".input-val").val('');
draw(rd_code);
return true;
}else{
alert('Error!');
document.getElementById("text").value='';
draw(rd_code);
return false;
}