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

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

    Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.

    I was also using a 'name' attribute rather than 'id' but this is the same approach.

    var pressedButtonName =
         typeof $(":input[type=submit]:focus")[0] === "undefined" ?
         $(":input[type=submit]:first")[0].name :
         $(":input[type=submit]:focus")[0].name;
    

提交回复
热议问题