Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda