jQuery submit, how can I know what submit button w

2019-01-22 22:08发布

I'm using ajaxSubmit plugin to send Ajax forms, but for some reason this plugin doesn't send names/values of input[type=image]'s. So now I'm catching the submit event before ajaxSubmit will handle the form and I need to know if it is possible to find out what button was pressed?

8条回答
Explosion°爆炸
2楼-- · 2019-01-22 23:07

This is what I am using (slight variation on the others, using mouseup and keyup events instead of focus):

var submitButton = undefined;
$('#your-form-id').find(':submit').live('mouseup keyup',function(){
    submitButton  = $(this);
});
$('#your-form-id').submit(function() {
    console.log(submitButton.attr('name'));
});
查看更多
Animai°情兽
3楼-- · 2019-01-22 23:13

This is how I solved it. I was inspired by some of the answers posted above but I needed an approach that would work for all my forms since I loaded them dynamically.

I noticed that the ajaxSubmit had a data option which described by the plugin does the following:

An object containing extra data that should be submitted along with the form.

This is exactly what we need.

So I attached the click handler on my submit buttons and saved the element using jQuery (I prefer this method than adding a fake attribute):

$('[type="submit"]').live('click', function(e){
        jQuery.data( $(this).parents('form')[0], 'submitTrigger', $(this).attr('name'));
});

And then in my ajaxSubmit call I built the data object and sent it like this:

function dialogFormSubmit( form ) {
    var data = {}
    data[jQuery.data( form, 'submitTrigger')] = true;
    $(form).ajaxSubmit({ 
        data: data
    });
    return false;
}

I built the data object that way because I wanted it to behave the same way as if I would have submitted it with vanilla HTML/PHP (name of the input is the key in the $_POST array). I suppose if I wanted to stay true to its real behaviour I would have added the value or innerHTML of the submit button but I usually just check if it's set so it was unncessary :).

查看更多
登录 后发表回答