skip to Main Content

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

2

Answers


  1. <form id="myForm" action="submit_handler.php" method="POST">
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Submit</button>
        </form>
    
        <script>
            $(document).ready(function() {
                $('#myForm').on('submit', function(event) {
                    event.preventDefault(); // Stop the default form submission
    
                    // Perform your custom validation or actions here
                    let isValid = true; // Replace with actual validation logic
    
                    if (isValid) {
                        // Manually submit the form if validation passes
                        this.submit();
                    } else {
                        // Handle validation failure (e.g., show error messages)
                        alert('Validation failed. Please correct the errors and try again.');
                    }
                });
            });
        </script>
    
    Login or Signup to reply.
  2. If I was to solve the same problem above I would use a different approach, my approach is highlighted below.

    1. I would wrap the inputs in a form

    2. Select Reset as the input of the second input

    3. Add an event listener to the form

    4. Prevent default event of the form

    5. Run the Ajax call

       <input type="submit" class="add">
       <input type="reset" class="cancel">
      

    // load jquery script

    <script>
    
    
    $('#form').submit(function(e){
    
        e.preventDefault()
    
        $.ajax({
            //.....
        })
    
    
    
    })
        
    
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search