[英]Required fields not working as form submits before validation
I am trying to get the required fields working but the form submits before the validation is done and I am not sure how I can fix it.我试图让必填字段正常工作,但表单在验证完成之前提交,我不确定如何修复它。 Is there anyway I can fix this?
无论如何我可以解决这个问题吗?
Apologies in advance for the messy code.提前为混乱的代码道歉。
<html>
<script>
function submitToAPI(e) {
e.preventDefault();
$.ajax({
type: "POST",
url : URL,
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
</script>
<body>
<form id="contact-form" method="POST">
<div class="formcontainer">
<div id='key'>
<label for="requestoremail"><strong>Requestor's Email Address</strong></label>
<input required class="defaultclass" id='requestoremail' type="text" placeholder="Enter your email address" name="requestoremail" >
<label for="purpose"><strong>Purpose of Request</strong></label>
<input required class="defaultclass" id='purpose'type="text" placeholder="Enter purpose of the key " name="purpose" >
</div>
<div id='secret'>
<label for="secretname"><strong>Secret Name</strong></label>
<input class="secretclass" id='secretname' type="text" placeholder="Enter name of secret" name="secretname" >
<label for="secretvalue"><strong>Secret Value </strong></label>
<input class="secretvalueclass" id='secretvalue' type="text" placeholder="Enter value of secret" name="secretvalue" >
</div>
<button form="contact-form" type="button" onClick="submitToAPI(event)" class="btn btn-lg" >Submit</button>
<script>
$(document).ready(function(){
$(".defaultclass").attr('required',true);
$(".secretclass").attr('required',false);
$("#secret").hide();
$("#key").show();
</script>
</body>
</html>
Your button has no knowledge of the form it resides inside.您的按钮不知道它所在的表单。 You only get automatic validation when the button's type is
submit
.只有当按钮的类型为
submit
时,您才会获得自动验证。 Because it is of type button
, it is just that, a button.因为它是
button
类型,所以它只是一个按钮。
However, you can programatically check if your form is valid before firing your ajax call但是,您可以在触发 ajax 呼叫之前以编程方式检查您的表单是否有效
// true if your form passes the validity check
const isValid = document.getElementById('contact-form').checkValidity();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.