我有一个表格,其中有用户 ID 可用性检查。因此,如果 ID 已在数据库中,它将显示一条消息“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>
此处的跨度将包含有关可用性的文本,
要跨越的值来自 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 已存在于数据库中,我无法阻止提交。所以请任何人帮助我。
最佳答案
只是因为您需要在函数的参数中传递事件:
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);"
<小时/>
Fiddle
<小时/>好的!正如 @Sanjeev 尝试评论这项工作的最佳方法,那么当您使用 jQuery 时,您可以按照Unobrusive 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
事件的文档中,请使用此方法。
Updated fiddle with unobtrusive way.
关于javascript - 如何防止基于 html 元素中的文本提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24241756/