jQuery: how to get which button was clicked upon f

2018-12-31 17:38发布

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 submit button was clicked without applying a .click() event to each one.

Here's the setup:

<html>
<head>
  <title>jQuery research: forms</title>
  <script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
  <script type='text/javascript' language='javascript'>
      $(document).ready(function(){
          $('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
      });
      function process_form_submission( event ) {
          event.preventDefault();
          //var target = $(event.target);
          var me = event.currentTarget;
          var data = me.data.value;
          var which_button = '?';       // <-- this is what I want to know
          alert( 'data: ' + data + ', button: ' + which_button );
      }
  </script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
  <input type='hidden' name='data' value='blahdatayadda' />
  <input type='submit' name='name1' value='value1' />
  <input type='submit' name='name2' value='value2' />
</form>
</body>
</html>

Live example on jsfiddle

Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?

标签: jquery forms
23条回答
低头抚发
2楼-- · 2018-12-31 18:14

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]');
})
查看更多
谁念西风独自凉
3楼-- · 2018-12-31 18:15

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;
查看更多
泪湿衣
4楼-- · 2018-12-31 18:17

I also made a solution, and it works quite well:
It uses jQuery and CSS


First, I made a quick CSS class, this can be embedded or in a seperate file.

<style type='text/css'>
    .Clicked {
        /*No Attributes*/
    }
</style>


Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).

    // Adds a CSS Class to the Button That Has Been Clicked.
    $("form :input[type='submit']").click(function () 
    {
        if ($(this).hasClass("Clicked"))
        {
            $(this).removeClass("Clicked");
        }
        $(this).addClass("Clicked");
    });


Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.

    // On Form Submit
    $("form").submit(function ()
    {
        // Test Which Button Has the Class
        if ($("input[name='name1']").hasClass("Clicked"))
        {
            // Button 'name1' has been clicked.
        }
        else
        {
           // Button 'name2' has been clicked.
        }
    });

Hope this helps! Cheers!

查看更多
浪荡孟婆
5楼-- · 2018-12-31 18:17

You want to use window.event.srcElement.id like this:

function clickTheButton() {

var Sender = window.event.srcElement;
alert("the item clicked was " + Sender.id)

}

for a button that looks like:

<input type="button" id="myButton" onclick="clickTheButton();" value="Click Me"/>

you will get an alert that reads: "the item clicked was myButton.

In your improved example you can add window.event.srcElement to process_form_submission and you will have a reference to whichever element invoked the process.

查看更多
柔情千种
6楼-- · 2018-12-31 18:18

This works for me:

$("form").submit(function() {
   // Print the value of the button that was clicked
   console.log($(document.activeElement).val());
}
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 18:18

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.

查看更多
登录 后发表回答