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

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

    Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.

    $('form.form-js').submit(function(event){
        var frm = $(this);
        var btn = $(document.activeElement);
        if(
            btn.length &&
            frm.has(btn) &&
            btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
            btn.is('[name]')
        ){
            frm.append('');
        }
    
        // Handle the form submit here
    
        $('#form-js-temp').remove();
    });
    

    Side note: I personally add the class form-js on all forms that are submitted via JavaScript.

提交回复
热议问题