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

221
Vistas
Why's my form action still being triggered when validating the form despite using e.preventDefault()?

I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.

I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.

I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?

html:

<form method="POST" id="form" action="/post.php">
  <span class="nameError"></span>
  <input type="text" class="name" name="name" placeholder="Name" required/>
            
  <input class="button" type="submit" value="Submit"/>
</form>

Here's my jquery:

let name = $('.name');
let nameError= $('.nameError');

$(document).ready(function() {

$('input[type=submit]').on('click', function(e) {
    if (name.length > 20) {
        e.preventDefault();
        nameError.val("Too many characters!");
        return false;
    }
 });

});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.

$(document).ready(function() {
    $("#form").submit(function( event ) {
     let name = $('.name').val();
     let nameError= $('.nameError');
        if (name.length > 20) {
            nameError.text("Too many characters!");
            event.preventDefault();
        }
     });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
  
  <input type="text" class="name" name="name" placeholder="Name" required/>
           <label class="nameError"></label> <br/>
  <input class="button" type="submit" value="Submit"/>
</form>

about 4 years ago · Juan Pablo Isaza 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