Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
AddClass doesn't work when ajax form is submitted

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!