views:

45

answers:

2

Hi there: For example, I have a HTML form with several input buttons,

 <form action="/index.php" method="post">
 <input type="hidden" name="hf" />
 <input type="submit" id="apply_action" name="action" value="Apply">
 <input type="submit" id="cancel_action" name="action" value="Cancel">

it's the current framework of a large web project. Once Submit button 'Apply' is clicked, it will map to a particular PHP function on the web server, and then return certain HTML code back; of course, once 'Cancel' is clicked, it will map to another PHP function.

Now, I would like to add some stuff before the original submit action when the 'Apply' is clicked. For example: I would like to add an javascript alert ("hello") before the original submit action is sent to the server? I dont know how to achieve this with Jquery? First of all, there are two submit actions for this form, value='Apply' or 'Cancel', I need to differentiate the action; Second, after alert('hello'), I still need the original form action='index.php' to be executed. Is there a jquery function for this purpose? Thanks!

+4  A: 

It sounds like you wish to bind a function to the form's submit event. See http://api.jquery.com/submit/

To fit your request, this should work:

$('form').submit(function(){
  alert('hello');
  return true;
  });

Addendum:

Okay, since you have two submit buttons, you'll need to use the click event.

$(document).ready(function(){
  $('input').click(function(ev){
   alert(ev.target.id);//this is how you will differentiate between the two buttons.
      //or, you could bind a separate click event to each one
   if(ev.target.id=="cancel_action"){ /* etc.. */ }
   else{ /* etc.. */ }
   });
 });

With either method, the form will be submitted on click. As noted by Francisco Soto, returning false will prevent the submission from either method. Returning true (or not specifying a return value) will continue with the form submission.

Alex JL
first of all, there are two submit actions for this form, value='Apply' or 'Cancel', I need to differentiate the action; second, after alert('hello'), I still need the original form action='index.php' to be excuted
WilliamLou
Or return false if you wish to prevent the form submitting.
Francisco Soto
Regarding your second note, the form does submit to the specified action, as before. Did you read the docs for submit, or try this code?
Alex JL
Anyhow, I've added a way to differentiate the buttons as it's correct, you can't do that by binding submit.
Alex JL
+3  A: 

You should use the .click() method for the button.

$('#apply_action').click(
   function(){
    // do your stuff here..
   }
);
Gaby