Ajit1991
Ajit1991

Reputation: 53

How can I prevent form submit action to be triggered?

This is my form where i have action event when I click on button.

<form id="prefForm4" enctype="multipart/form-data" method="post" class="masters"
    action="/Preferences/Preferences/RISSave">
</form>

I have two button which I will display them depending on some condition say when button1 is displayed it will perform the form action and when button2 is displayed it will trigger javascript function which perform the different action and it should not trigger form action, but I my case both methods are triggering.

<input id="button1" name="Save" class="button" type="submit" value="<%="Save".Localize()%>"/>

<input id="button2" name="Save" class="button" type="submit" value="<%="Save".Localize()%>"
                        onclick="saveData();" />

JavaScript below

function saveData() {
        $.ajax({
            url: "/Preferences/Preferences/saveData",
            type: "POST",
            data: items,
            success: function (reponse) {
                return true;
            },
            error: function (reponse) {

            }
        });
    }

Please help me on this. Thanks in advance.

Upvotes: 1

Views: 1460

Answers (4)

Mamun
Mamun

Reputation: 68933

Change your second button type from submit to button This will prevent the submission of the form.

<input id="button2" name="SavePACS" class="button" type="button" value="<%="SavePACS".Localize()%>"
                    onclick="saveData();" />

Upvotes: 4

treyBake
treyBake

Reputation: 6560

you can do it like this:

$('form').on('submit', function(e)
{
    e.preventDefault(); //this prevents default action

    //whatever else you want to do

    $('form').submit()
})

Upvotes: 3

Jason McFarlane
Jason McFarlane

Reputation: 2175

Change where you call your function, instead of calling it inline create an event listener and then you prevent default actions

$('input[name=SavePACS]').on('click', function(e) {
    e.preventDefault()

    // then do your code here
});

Upvotes: 2

Hacky
Hacky

Reputation: 323

you should make the buttons not of type submit to prevent them from triggering the form submission.

Upvotes: -1

Related Questions