如何防止基于html元素中的文本提交表单
How to prevent submitting form based on text in an html element?
我有一个表单,我有用户Id可用性检查。因此,如果Id已经在DB中,它将显示一条消息"Id已经在使用中"。在这种情况下,我不得不避免提交表格。为此,我的html如下,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
这里span将包含关于可用性的文本,
span的值来自jquery post调用,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
这个很好,为了防止提交,我写了一个javascript函数,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
一切都很好,但这个javascript函数不工作很好,所以我不能阻止在Id已经存在于DB的情况下提交。所以请大家帮帮我
因为您需要在函数的参数中传递事件:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
根据您的评论,您可以将事件传递给onclick
处理程序中的函数:
onclick="checkTeacherId(event);"
小提琴
好吧!@Sanjeev试图评论最佳方法对于这项工作,那么当你使用jQuery时,那么你可以按照最佳方法这样做,如 unbrusive Javascript(删除这个内联脚本,就像上面发布的):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
如果您想将脚本外部化,如在全局范围内声明函数并将事件处理程序放在文档中,使用submit
事件,请使用此方法。
以不引人注目的方式更新小提琴
根据表单验证最佳实践的解决方案:
你已经实现表单提交通过提交按钮,而不是通过js像document.getElementById("myForm").submit();
我不认为在提交按钮上使用onclick处理程序进行验证有任何意义,使用原生的onsubmit事件属性,否则你将继续破坏提交流程。Onsubmit用于验证表单并在验证失败时停止表单提交。这在所有浏览器中都可以正常工作,并且是表单验证的正确方法
的例子:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}
相关文章:
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- ng在下拉列表和文本区域提交
- 使用加号按钮添加多个文本框,并通过PHP提交
- 查找已提交的文本区域数
- 提交表单后,Watir文本框输入未持续(重置为以前的文本框输入)
- 提交表单时,Javascript(JQuery)不会在文本区域中填充内容
- 为提交文本区域添加输入
- 使用javascript提交表单并从字段/单选框/复选框/文本区域获取数据
- 提交按钮只能在onchange调用输入文本后第二次点击时工作
- 移动HTML输入文本框在提交时隐藏软键盘
- 使用回车按钮提交文本框表单
- 为什么在文本框内按回车键,单击第一个按钮并提交表单
- 如何在没有表单提交、没有js、没有jquery和没有ajax的情况下将输入的文本框值存储到php变量中
- 清除按钮提交后的文本区域
- 你能提交一个带有文本输入数组的表单吗
- 在提交之前创建文本区域预览
- 删除文本区域文本提交在新的选项卡
- 如何防止基于html元素中的文本提交表单
- 如何从下面的代码中获取文本“提交”
- 防止控制器文本提交失败