简体   繁体   中英

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;
    }
 });

});

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM