I'm trying to create a validation for my ajax form. I want to make a red border around the input when it's empty when you submit the form.
Unfortunately, addClass() doesn't work. The alert shows up, but that's all.
$(function() {
$('#form').on('submit', function(e) {
e.preventDefault();
if ($('.required').val() === '') {
$('.required').addClass('error');
alert("error");
}
$.ajax({
type: "post",
url: 'php/php.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function() {
document.getElementById("text").innerHTML = "success";
document.getElementById("add").style.border = "2px solid green";
},
error: function() {
document.getElementById("text").innerHTML = "error";
document.getElementById("add").style.border = "2px solid red";
}
});
});
});
.error {
border: solid 2px red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="form" method="POST" action="php/php.php">
Name:
<input type="text" name="Name" id="name" class="required"><br>
<input type="submit" name="Add" id="add">
</form>
I checked out some other posts, but still can't resolve the issue.
Edit: It seems that xampp had some problems importing external CSS files (or at least updating the data). The issue is resolved.
Are you using jquery UI?, because addClass is an async function in jquery ui and thus, alert statement in the next line is ran first which blocks the main thread.