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

220
Views
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 answers
Answer question

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 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!