如何防止基于html元素中的文本提交表单

How to prevent submitting form based on text in an html element?

本文关键字:文本 提交 表单 元素 何防止 html      更新时间:2023-09-26

我有一个表单,我有用户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;
 }
}