jquery detect which button submitted form

て烟熏妆下的殇ゞ 提交于 2019-12-08 16:49:28

问题


I have a form with the following:

<form id="my-form" ...>
    ...
    <button type="submit" name="bttnsubmit" value="1">The first button</button>
    <button type="submit" name="bttnsubmit" value="2">The last button</button>
</form>

I'd like to detect which triggered the form submit event using just:

$('#my-form').submit(function(){
    //psuedo code
    if($('[name=bttnsubmit]').val() == 1) {
        ....
    }
});

Obviously that selector will always return the value of the first bttnsubmit element it comes across, so I need some other magic selector or filter or something.

I have seen $('[name=bttnsubmit][clicked=true]') touted about but that has not yet worked in my attempts...

I could of course resort to $('[name=bttnsubmit]').click() but would prefer to be able to achieve my goals in the forms submit event.

Any help/tips much appreciated.


回答1:


I don't know if there is any built in event data (maybe there is) but one idea that comes to mind is to handle the click event of the buttons and store a global reference of the value. Something like this:

var ButtonValue;

$('button[type="submit"]').click(function(e){
   ButtonValue = $(this).val();
});

$('#my-form').submit(function(){
    //psuedo code
    if(ButtonValue == 1)
    {
        ....
    }
});



回答2:


This answer is an improvement of @musefan's answer.

Avoid global variables. It is better to keep data in form:

$('button[type=submit]').click(function (e) {
    var button = $(this);
    buttonForm = button.closest('form');
    buttonForm.data('submittedBy', button);
});

And in submit handler just get it:

$('#my-form').submit(function (e) {
    var form = $(this);
    var submittedBy = form.data('submittedBy');
    if(submittedBy.val() == 1) {
        // Any code here...
    }
});

Form could be submitted by hitting 'enter'. To avoid null in submittedBy variable:

var submittedBy = form.data('submittedBy') || form.find('button[type=submit]:first');



回答3:


Regarding your statement:

I have seen $('[name=bttnsubmit][clicked=true]') touted about but that has not yet worked in my attempts...

I found this to not be explained correctly elsewhere. It's not an automatic thing. You still need to set it up by adding the "clicked" attribute any time a submit button is clicked.

$("#my-form input[type=submit]").click(function () {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});
$("#my-form").submit(function () {
    var clickedSubmitValue = $("input[type=submit][clicked=true]").val();
    if (clickedSubmitValue == "1")
    {
        ...
    }
});

Similar to example here.



来源:https://stackoverflow.com/questions/14628750/jquery-detect-which-button-submitted-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!