简体   繁体   English

如何防止表单提交操作被触发?

[英]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. 我有两个按钮,我将根据某些条件显示它们,例如,当显示button1时,它将执行表单操作;当显示button2时,它将触发执行不同操作的javascript函数,并且不应触发表单操作,但是我两种方法都触发的情况。

<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 下面的JavaScript

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. 提前致谢。

Change your second button type from submit to button This will prevent the submission of the form. 将第二个按钮类型从“ submit更改为“ button这将阻止提交表单。

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

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()
})

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
});

你应该做的按钮类型的提交,以防止它们触发表单提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM