Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 348
newbie Avatar asked Jan 28 '10 11:01

newbie


4 Answers

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);
    });
});
like image 92
karim79 Avatar answered Sep 23 '22 13:09

karim79


$("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 ;)

like image 22
cusspvz Avatar answered Sep 22 '22 13:09

cusspvz


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'));
});
like image 23
thaddeusmt Avatar answered Sep 19 '22 13:09

thaddeusmt


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);
    }
  });
});
like image 38
drupalfever Avatar answered Sep 23 '22 13:09

drupalfever