How can I void a form action and execute jQuery when all HTML form elements are validated?
Asked Answered
H

6

36

I have a simple HTML form that I want to leverage for required field validation. My issue is that I want to use the HTML5 form validation BUT at the same time avoid actually submitting the form because I want to execute a jQuery Ajax call instead. I know you can disable html5 validation, but I want to keep this as my primary method of form validation instead of a jQuery plugin.

Any thoughts?

HTML

<form action="donothing" id="membershipform" method="get" accept-charset="utf-8">
    <input type="text" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="first and last name" required>
    <input type="email" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="email" required>
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="phone" required>    
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="mailing address" required>      
    <input type="phone" class="borderr3 innershadow3" name="some_name" value="" id="some_name" placeholder="how you heard about us" required>
    <p>
        <input type="submit" id="submitbtn" class="submitbtn" value="Continue" style="width:265px">
    </p>
</form> 

JavaScript:

$(function(){
  $("#submitbtn").click(function(){
    $.ajax({
      url: "<?php bloginfo('template_url') ?>/ajax-membership.php",
      success: 
      function(txt){
        if(txt){
          $("#thankyou").slideDown("slow");
        }
      }
    });
  });
});
Harbor answered 16/4, 2011 at 17:1 Comment(0)
N
57

According to this: Do any browsers yet support HTML5's checkValidity() method?, and this may not be the latest truth since HTML5 is a work in progress, the Form.checkValidity() and element.validity.valid should let you access validation information from JavaScript. Assuming that's true, your jQuery would need to attach itself to the form submit and make use of that:

$('#membershipform').submit(function(event){
    // cancels the form submission
    event.preventDefault();

    // do whatever you want here
});
Newell answered 16/4, 2011 at 18:57 Comment(4)
To all readers: MAKE SURE to include the event parameter in the function, otherwise this WILL NOT work in Firefox.Hyaluronidase
@Max, do you mean to make sure to pass the event parameter to the callback function? If so, yes, that's certainly required in all browsers as you couldn't call preventDefault otherwise.Newell
Yes. Just as a reminder. I wasted a good bit of time trying to figure out why it wasn't working after just using the event.preventDefault(); and not the rest of the example. Even without the event parameter, it still seemed to behave as desired on Chrome, but not Firefox.Hyaluronidase
@Max - what you might have there is that Chrome automatically has some automatic validation behavior that also prevents the submitting of the form. So this code would not be needed at all, but event.preventDefault() would throw an error on the console if you were using it without event being defined. So make sure to keep that console open. Stay safe out there! :)Newell
C
15

You can use html5 form validation from javascript, only call to method reportValidity()

In your example:

<script>
    document.querySelector('#membershipform').reportValidity()
</script>

reportValidity run html5 form validation and return true/false.

Campanile answered 30/10, 2019 at 8:47 Comment(1)
This answer would benefit from further details: What to do with the return value, and where to put this element?Julian
W
4

Use:

$('#membershipform').submit(function(){
    // do whatever you want here

    return false;
});
Ways answered 9/8, 2011 at 22:4 Comment(2)
This won't work if the code above the return statement throws an error. In case of an error the form still go to the address specified in the "action" attribute.Sowens
Yes! this works if I want my form to go through the validation part but not submit. good jobPart
N
4

This is a subtle leverage of default behaviour and javascript to create what you want.

var form = document.getElementById("purchaseForm");
if(form.checkValidity()){
    console.log("valid");
    e.preventDefault();
}else{
    console.log("not valid");
    return;
}

If the form is valid then preventDefault() and continue with your function (e.g. send over ajax). If not valid then return without preventing default, you should find the default actions for form validation occurs on your form inputs.

Niemi answered 21/9, 2017 at 15:28 Comment(1)
This worked for me. It helped me check if all input fields were valid. I did not use e.preventDefault();, instead, I put my code that stored the form in the if statement.Chandelle
P
1

Using pure java script

<script>

    document.getElementById('membershipform')
        .addEventListener("submit", 
            function(event) {
                event.preventDefault();

                // write stuff

            });

</script>
Perturb answered 7/12, 2016 at 5:34 Comment(0)
J
0

As HTML/JavaScript: Execute form submit checks on button-press; is it possible in an elegant way? was closed because of being a duplicate of How can I void a form action and execute jQuery when all HTML form elements are validated?, I could not add an answer there.

So I add my solution here instead:

I used

if (!document.forms[0].reportValidity())
    return;         // invalid input, ignore button

at the beginning of by onClick handler (my document just has one form). Firefox pops up hints for all incorrect input fields, so the handler does not have to deal with those. Thus I simply ignore the button press while the input is invalid.

Julian answered 3/11, 2023 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.