在提交表格之前如何做事?

时间:2010-07-31 00:26:03

标签: php jquery form-submit

例如,我有一个带有几个输入按钮的HTML表单,

 <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">

它是大型Web项目的当前框架。单击提交按钮“应用”后,它将映射到Web服务器上的特定PHP功能,然后返回某些HTML代码;当然,一旦点击“取消”,它将映射到另一个PHP函数。

现在,我想在单击“应用”时在原始提交操作之前添加一些内容。例如:我想在将原始提交操作发送到服务器之前添加javascript警报(“hello”)?我不知道如何使用Jquery实现这一目标?首先,这个表单有两个提交动作,值='应用'或'取消',我需要区分动作; 其次,在警告('hello')之后,我仍然需要执行原始表单action ='index.php'。 是否有用于此目的的jquery函数?谢谢!

2 个答案:

答案 0 :(得分:4)

听起来您希望将函数绑定到表单的submit事件。见http://api.jquery.com/submit/

为了满足您的要求,这应该有效:

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

附录:

好的,由于你有两个提交按钮,你需要使用click事件。

$(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.. */ }
   });
 });

使用任何一种方法,表单都会在点击时提交。正如Francisco Soto所指出的那样,返回false会阻止任何一种方法的提交。返回true(或不指定返回值)将继续提交表单。

答案 1 :(得分:3)

您应该使用按钮的.click()方法。

$('#apply_action').click(
   function(){
    // do your stuff here..
   }
);
相关问题