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. Because it is of type button, it is just that, a button.
However, you can programatically check if your form is valid before firing your ajax call
// true if your form passes the validity check
const isValid = document.getElementById('contact-form').checkValidity();