jQuery: how to get which button was clicked upon form submission?

后端 未结 26 1754
旧巷少年郎
旧巷少年郎 2020-11-22 16:01

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I\'d like to know which submi

26条回答
  •  鱼传尺愫
    2020-11-22 16:36

    As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute

    $(document).on('click', '[type=submit]', function() {
        var form = $(this).prop('form') || $(this).closest('form')[0];
        $(form.elements).filter('[type=submit]').removeAttr('clicked')
        $(this).attr('clicked', true);
    });
    
    $('form').on('submit', function() {
        var submitter = $(this.elements).filter('[clicked]');
    })
    

提交回复
热议问题