jQuery submit, how can I know what submit button was pressed?
Asked Answered
F

8

10

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?

Friedly answered 28/1, 2010 at 11:18 Comment(0)
M
7
$("input .button-example").click(function(){
//do something with $(this) var
});

PS: do you have jQuery controling the $ var? Otherwise you have to do this:

jQuery.noConflict();
jQuery(document).ready(function(){
    jQuery("input .button-example").click(function(){
    //do something with jQuery(this) var
       alert(jQuery(this));
    });
});

if you wan't control on event (form submit)

$(document).ready(function(){
    $("#formid").submit(function() {
          alert('Handler for .submit() called.');
          return false;
    });
});

tell me something if it worked ;)

Morehouse answered 28/1, 2010 at 11:23 Comment(1)
I used something like that. I binded click to that other button and added hidden field to, so now server gets proper information...Friedly
R
19

This will catch whichever input element initiated the submit:

$(document).ready(function() {
    var target = null;
    $('#form :input').focus(function() {
        target = this;
        alert(target);
    });
    $('#form').submit(function() {
        alert(target);
    });
});
Ripple answered 28/1, 2010 at 11:32 Comment(2)
This works way better if you do $('#form :input').click(function() { with click instead of focus.Anaphylaxis
click will not be triggered if you press return.. may be you need to use [...].bind('click focus', function() {[...]})[...]Cascara
M
7
$("input .button-example").click(function(){
//do something with $(this) var
});

PS: do you have jQuery controling the $ var? Otherwise you have to do this:

jQuery.noConflict();
jQuery(document).ready(function(){
    jQuery("input .button-example").click(function(){
    //do something with jQuery(this) var
       alert(jQuery(this));
    });
});

if you wan't control on event (form submit)

$(document).ready(function(){
    $("#formid").submit(function() {
          alert('Handler for .submit() called.');
          return false;
    });
});

tell me something if it worked ;)

Morehouse answered 28/1, 2010 at 11:23 Comment(1)
I used something like that. I binded click to that other button and added hidden field to, so now server gets proper information...Friedly
E
5

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'));
});
Emory answered 15/10, 2011 at 12:21 Comment(0)
R
2

Following is what I think would be a more comprehensive example of how to accomplish what you asked. You should replace the "#your-form" with your id form and replace "Button One" & "Button Two" with the values on your form buttons.

$(document).ready(function() {
  var target = null;
  $('#your-form-id :input').focus(function() {
    target = $(this).val();
  });
  $('#your-form-id').submit(function() {

    if (target == 'Button One') {
      alert (target);
    }
    else if (target == 'Button Two') {
      alert (target);
    }
  });
});
Radioman answered 18/8, 2011 at 18:42 Comment(0)
Y
2

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 :).

Younker answered 6/9, 2011 at 20:58 Comment(1)
by far the best answer i've seen.Fimbriation
T
2

I found this very useful. It covers the case of clicking, and also submitting with tab index and hitting space or enter. It captures the last input before a submit was made, and that's the button which submitted, so you can have several buttons and check each as a target to perform something unique.

$('#form input').live('focusin focusout mouseup', function() {
    // Add a data attribute to the form and save input as last selected
    $('#form').data('lastSelected', $(this));
});
$('#form').submit(function() {
    var last = $(this).data('lastSelected').get(0);
    var target = $('#button').get(0);
    console.log(last);
    console.log(target);
    // Verify if last selected was our target button
    if (last == target) {
        console.log('bingo');
        return false;
    }
});
Tudela answered 25/9, 2012 at 15:2 Comment(0)
T
1
$(document).ready(function() {
    var clickedVar = null;
    $('#form :submit').focus(function() {
         clickedVar = $(this).attr("name");
         alert(clickedVar);
    });
});
Tensive answered 28/1, 2011 at 20:43 Comment(0)
P
0

Hi the answer did not convince me so much here to bring an alternative. What I will do is verify by JS which button was pressed.

<head>
<script>
$('body').click(function(event) {
     var log = $('#log');
     if($(event.target).is('#btn1')) {
        log.html(event.target.id + ' was clicked.');
        return false;
    }else{
        if($(event.target).is('#btn2')) {
           log.html(event.target.id + ' was clicked.');
           return false;
              }
         }
});
</script>
</head>
<body>
   <form id="formulario"  method="post">
      <div id="log"></div>
      <input type="submit" id="btn1" value="Btn 01">
      <input type="submit" id="btn2" value="Btn 02">
  </form>
</body>

Use this page to make the test Test

Saludos

Paddock answered 4/11, 2015 at 23:0 Comment(1)
This won't work when you sumbit a form using keyboard.Salmonella

© 2022 - 2024 — McMap. All rights reserved.