I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty.
Unfortunately, when I try to use addClass()
, it does not seem to have any effect. The alert message appears, but the border remains unchanged.
$(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>
Despite checking other resources and posts, I am still unable to find a solution to this issue.
Edit: It turns out that xampp was encountering problems with importing external CSS files (or updating the data). Fortunately, the problem has now been resolved.