Search code examples
javascripthtmlajaxformsyui-pure-css

PureCSS stop page reload on form submit but retain form validation


I'm trying to use PureCSS forms in my web app and I can't figure out how to retain the nifty form validation while stopping the page reload.

I know I can stop the page reload using onsubmit="return false;"

Then I can use AJAX to post the form data using onClick="PostSettings();", where PostSettings() is my javascript function containing the AJAX request. I also have to include event.preventDefault(); at the top of that function to stop the reload.

Unfortunately these steps which stop the reload also stop the nice in-built PureCSS validation.

Is there a way to retain that without triggering the page reload or will I need to make my own validation in the javascript?

FYI, here's the html:

<button type="submit" class="pure-button pure-input-1-2 pure-button-primary"
  id="save-simulation-button" onClick="PostSettings();" 
  onsubmit="return false;">
    <i     class="fa fa-save"></i> Submit Simulation Parameters
</button>

Solution

  • Thanks for your replies Lucas and Vignesh -- they didn't quite solve the problem, but they got me thinking and I developed a solution:

    In the html I had to add a return here: onClick="return PostSettings();"

    Then in the javascript I return true or false depending on whether or not the form passes validation, which I have to check:

    function PostSettings() {
        //event.preventDefault(); <<- commented out per Vigneshs suggestion
    
        var name = $("#simulation-name").val(); // jquery to get form values
        var description = $("#description").val();
    
        // Code to validate form: name and description cannot be blank
        if (name === "" || description === "") {
            console.log("name or description fields cannot be blank");
            return true; // <<- returning true allows PureCSS validation to continue
        }
    
        // Code passed validation so post the data...
        // POST code omitted for brevity
    
        return false; // <<- returning false stops the page reload
    }
    

    So in summary, returning true allows the PureCSS form validation to take place as per normal (and there's no page reload because the form hasn't passed validation). And when the form passes validation I return false to stop the page reload -- this also stops any other default events of the PureCSS form, but that's okay because I manually checked if it validated in the javascript.

    Hope this helps others who want to accomplish this in the future!