开发者

how to do stuff before submitting a form?

For example, I have a HTML form with s开发者_JS百科everal 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!


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜