jquerysubmit

jQuery - submit form after preventdefault


I've looked at lots of suggestions but none of them are working for me.

The form has two submit buttons, one for add .add and the other for cancel .cancel

<input type="submit" name="submit" value="Add" class="add">
<input type="submit" name="submit" value="Cancel" class="cancel">

I'm using the following jquery to do an ajax request and depending on the result I want an alert or the form to submit.

$('body').on( 'click', '.add', function (e) {
    e.preventDefault()
$.ajax({
    #do ajax request, 
    success: fucntion( res ) {

       if ( res.length >= 1 ) {
         alert ( res )
       } else {
         #submit form here
       }

   }
})

I've tried:

$('input[type="submit"]').submit()
$('.add').submit()
$('.add').trigger()

But it fails to submit the form. Adding some debug to the if / else I can see it is at the correct part of the script.

Any idea how I get this to work ? Thanks


Solution

  • I got this working using the following:

    $('body').on( 'click', '.add', function (e) {
    
        if ( ! $(this).data('complete' ) ) {
            e.preventDefault()
            
            $.ajax({
                #do ajax request, 
            success: fucntion( res ) {
                if ( res.length >= 1 ) {
                    alert ( res )
                } else {
                    $('.add').data('complete', true).click()
                }
            }
            })
        }
    })
    

    Thanks