Monday, 30 November 2020

How to prevent page reload after submit button clicked for bootstrap modal and parsley.js validation?

I have bootstrap modal which open up a modal to allow user to enter the form and it works. I implemented parseley.js for the form validaton and it kinda works. The problem is when the validation passed, it reload the page (as you can see from below gif) which it not the behavior I expect. What I expect is to see the alert('ok') in validateForm().

enter image description here

This is how I define my form tag and submit button

<form id="myForm" data-parsley-validate="">
    <button class="btn btn-default" >Save</button>           
</form>

and this is my function to validate the form using Parsely.js. When all validation pass, I expect is to see the alert('ok') but it doesn't. Instead, it reload the page.

function validateForm() {
    $('#myForm').parsley().on('field:validated', function () {
        debugger
        var ok = $('.parsley-error').length === 0;
        $('.bs-callout-info').toggleClass('hidden', !ok);
        $('.bs-callout-warning').toggleClass('hidden', ok);
    })

        .on('form:submit', function () {
            debugger
            alert('ok') // I expect to reach here when pass validation pass but it doesn't
            postCustomer();
            return false; 
        });
}

and this is my bootstrap modal

$('#modalCustomerForm').on('shown.bs.modal', function () {
    debugger
    validateForm();
    return false;
})

If I add sample code below, there is no css class added by parsley. I suspect parsley is not loading. But then, the validation work. When I press Submit button, I can see red color error message at the bottom of the textbox.

<div class="bs-callout bs-callout-warning hidden">
    <h4>Oh snap!</h4>
    <p>This form seems to be invalid :(</p>
</div>

<div class="bs-callout bs-callout-info hidden">
    <h4>Yay!</h4>
    <p>Everything seems to be ok :)</p>
</div>

Further troubleshooting. If I add an id to the button and create button click event, it doesn't auto reload the page. But if I do so, parsley.js validation doesn't work.

<button class="btn btn-default" type="submit" id="formBtn">Save</button>

$('#formBtn').on("click", function (e) {
    debugger

    postCustomer();
    debugger
    e.preventDefault();
})

That's why I put my postCustomer() at here (below) in validateForm() but it doesn't work either:

.on('form:submit', function () {
    
    debugger
    alert('ok')
    postCustomer();
    return false; // Don't submit form for this demo
});


from How to prevent page reload after submit button clicked for bootstrap modal and parsley.js validation?

No comments:

Post a Comment