Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda