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

后端 未结 26 1331
旧巷少年郎
旧巷少年郎 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:42

    I have found the best solution is

    $(document.activeElement).attr('id')
    

    This not only works on inputs, but it also works on button tags. Also it gets the id of the button.

    0 讨论(0)
  • 2020-11-22 16:45

    You can create input type="hidden" as holder for a button id information.

    <input type="hidden" name="button" id="button">
    <input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
    

    In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

    0 讨论(0)
  • 2020-11-22 16:46

    Here is my solution:

       $('#form').submit(function(e){   
            console.log($('#'+e.originalEvent.submitter.id));
            e.preventDefault();
        });
    
    0 讨论(0)
  • I found that this worked.

    $(document).ready(function() {
        $( "form" ).submit(function () {
            // Get the submit button element
            var btn = $(this).find("input[type=submit]:focus" );
        });
    }
    
    0 讨论(0)
  • 2020-11-22 16:47

    I write this function that helps me

    var PupulateFormData= function (elem) {
    var arr = {};
    $(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
        arr[$(this).attr("name")] = $(this).val();
    });
    return arr;
    };
    

    and then Use

    var data= PupulateFormData($("form"));
    
    0 讨论(0)
  • 2020-11-22 16:49

    When the form is submitted:

    • document.activeElement will give you the submit button that was clicked.

    • document.activeElement.getAttribute('value') will give you that button's value.

    Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."

    0 讨论(0)
提交回复
热议问题