Aerodynamika
Aerodynamika

Reputation: 8413

How to catch a form submit action in JavaScript/jQuery?

I have a form that the user can submit using the two following buttons:

<input type="submit" name="delete" value="delete" id="deletebutton" class="pure-button">
<input type='submit' id="submitbutton" name="btnSubmit" value="save" class="pure-button pure-button-primary">

I have an submit event listener that loads a certain function I need to process the form (the form has id #submitform):

document.querySelector('#submitform').addEventListener('submit', function(e) {
    e.preventDefault();
    // Some code goes here
});

However, this code only reacts when #submitbutton is clicked. When #deletebutton is clicked the form submits as usual.

How do I avoid that and have another function listening to whether #deletebutton is clicked?

Thank you!

Upvotes: 1

Views: 4599

Answers (2)

Anto king
Anto king

Reputation: 1222

Why dont you simply try like below

 $("#submitform").submit(function(event){
    var isValid = true;

    // do all your validation if need here

    if (!isValid) {
        event.preventDefault();
    }
});

Make sure both the buttons inside the form closing tag and your event listener was not properly closed

 document.querySelector('#submitform').addEventListener('submit', function(e) {
    e.preventDefault();
    // Some code goes here
});

Upvotes: 3

joshvito
joshvito

Reputation: 1563

I would add another listenter for the delete button.

document.querySelector('#deletebutton').addEventListener('submit', function(e) {
    e.preventDefault();
    // Some code goes here
    // commonFunct() { ... }
}

If both buttons will perform common code/action you can call a common function so you don't have to repeat yourself.

Upvotes: 2

Related Questions