How can I get the button that caused the submit fr

2019-01-01 13:37发布

I'm trying to find the value of the submit button that triggered the form to submit

$("form").submit(function() {

});

I could possibly fire a $("input[type=submit]").click() event for each button and set some variable, but that seems less elegant than some how pulling the button off of the the form on submit.

13条回答
妖精总统
2楼-- · 2019-01-01 13:42

I did try some of the examples provided, but they didn't work for our purposes.

Here's a fiddle to show: http://jsfiddle.net/7a8qhofo/1/

I was faced with a similar issue, and this is how we solved the issue in our forms.

$(document).ready(function(){

    // Set a variable, we will fill later.
    var value = null;

    // On submit click, set the value
    $('input[type="submit"]').click(function(){
        value = $(this).val();
    });

    // On data-type submit click, set the value
    $('input[type="submit"][data-type]').click(function(){
        value = $(this).data('type');
    });

    // Use the set value in the submit function
    $('form').submit(function (event){
        event.preventDefault();
        alert(value);
        // do whatever you need to with the content
    });
});
查看更多
看风景的人
3楼-- · 2019-01-01 13:43

you can try this way with "event.originalEvent.x" and "event.originalEvent.y":

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <title>test</title>
</head>
<body>

    <form id="is_a_form">
        <input id="is_a_input_1" type="submit"><br />
        <input id="is_a_input_2" type="submit"><br />
        <input id="is_a_input_3" type="submit"><br />
        <input id="is_a_input_4" type="submit"><br />
        <input id="is_a_input_5" type="submit"><br />
    </form>

</body>
</html>
<script>
$(function(){

    $.fn.extend({
      inPosition: function(x, y) {

        return this.each(function() {

            try{
                var offset = $(this).offset();

                if ( (x >= offset.left) &&
                     (x <= (offset.left+$(this).width())) &&
                     (y >= offset.top) &&
                     (y <= (offset.top+$(this).height())) )
                {
                    $(this).css("background-color", "red");
                }
                else
                {
                        $(this).css("background-color", "#d4d0c8");
                }
                }
                catch(ex)
                {
                }

        });
      }
    }); 

    $("form").submit(function(ev) {

        $("input[type='submit']").inPosition(ev.originalEvent.x ,ev.originalEvent.y);
        return false;

    });

});
</script>
查看更多
千与千寻千般痛.
4楼-- · 2019-01-01 13:44

( event )

function submForm(form,event){
             var submitButton;

             if(typeof event.explicitOriginalTarget != 'undefined'){  //
                 submitButton = event.explicitOriginalTarget;
             }else if(typeof document.activeElement.value != 'undefined'){  // IE
                 submitButton = document.activeElement;
             };

             alert(submitButton.name+' = '+submitButton.value)
}


<form action="" method="post" onSubmit="submForm(this, event); return false;">
查看更多
刘海飞了
5楼-- · 2019-01-01 13:46

With a more specific event handler and JQuery, your event object is the button clicked. You can also get the delegating form from this event if needed.

$('form').on('click', 'button', function (e) {
  e.preventDefault();
  var
    $button = $(e.target),
    $form = $(e.delegateTarget);
  var buttonValue = $button.val();
});

This Doc has everything you need to get started. JQuery Doc.

查看更多
深知你不懂我心
6楼-- · 2019-01-01 13:47

I leveraged document.activeElement as sketched in this answer: How to get the focused element with jQuery?

$form.on('submit', function() {
    var $btn = $(document.activeElement);

    if (
        /* there is an activeElement at all */
        $btn.length &&

        /* it's a child of the form */ 
        $form.has($btn) &&

        /* it's really a submit element */
        $btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&

        /* it has a "name" attribute */
        $btn.is('[name]')
    ) {
        console.log("Seems, that this element was clicked:", $btn);
        /* access $btn.attr("name") and $btn.val() for data */
    }
});

I take advantage of the fact, that the button is always the focused element after clicking it. This will not work, if you do a blur() right after the click.

@Doin has spotted another drawback. If a user submits the form via enter in a text field, the document.activeElement is not set. You'd need to watch out for this yourself, by handling keypress events in input[type="text"] and similar.

Update 2017-01: For my library Hyperform I chose not to use activeElement but to catch all events, that lead to form submission. The code for this is on Github.

If you happen to use Hyperform, this is how you would access the button that triggered the submit:

$(form).on('submit', function(event) {
  var button = event.submittedVia;
});
查看更多
看淡一切
7楼-- · 2019-01-01 13:47

I searched and found several ways to get the submit button name + value sent to the server using jQuery + AJAX. I didn't like them very much...

One of the bests was hunter's solution presented here!

But I wrote another one myself.

I want to share, because it is good, and, as I needed, it works also with forms loaded via ajax (after document.ready):

$(document).on('click', 'form input[type=submit]', function(){
    $('<input type="hidden" />').appendTo($(this).parents('form').first()).attr('name', $(this).attr('name')).attr('value', $(this).attr('value'));
});

Simple! When the submit button is clicked, a hidden field is added to the form, using same name and value of the submit button.

EDIT: The version below is easier to read. Also, it takes care of removing previously appended hidden fields (in the case of submitting the same form twice, which is perfectly possible when using AJAX).

Improved code:

$(document).on('click', 'form input[type=submit]', function(){
    var name   = $(this).attr('name');
    if (typeof name == 'undefined') return;
    var value  = $(this).attr('value');
    var $form  = $(this).parents('form').first();
    var $input = $('<input type="hidden" class="temp-hidden" />').attr('name', name).attr('value', value);
    $form.find('input.temp-hidden').remove();
    $form.append($input);
});
查看更多
登录 后发表回答