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

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

    Similar to Stan answer but :

    • if you have more than one button, you have to get only the first button => [0]
    • if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId

    $(document).on('submit', function(event) {
        event.preventDefault();
        var pressedButtonId = 
             typeof $(":input[type=submit]:focus")[0] === "undefined" ? 
             "myDefaultButtonId" :
             $(":input[type=submit]:focus")[0].id;
        ...
     }
    

提交回复
热议问题