【问题标题】:how to do stuff before submitting a form?提交表单前怎么做?
【发布时间】:2010-07-31 00:26:02
【问题描述】:

例如,我有一个带有多个输入按钮的 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 服务器上的特定 PHP 函数,然后返回某些 HTML 代码;当然,一旦点击“取消”,它就会映射到另一个 PHP 函数。

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

【问题讨论】:

    标签: php jquery form-submit


    【解决方案1】:

    听起来您希望将函数绑定到表单的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.. */ }
       });
     });
    

    无论使用哪种方法,都将在点击时提交表单。正如弗朗西斯科索托所指出的,返回 false 将阻止从任一方法提交。返回 true(或未指定返回值)将继续提交表单。

    【讨论】:

    • 首先,这个表单有两个提交动作,value='Apply'或者'Cancel',我需要区分动作;其次,在alert('hello')之后,我还需要执行原来的表单action='index.php'
    • 如果您希望阻止表单提交,则返回 false。
    • 关于您的第二个注释,表单确实像以前一样提交到指定的操作。您是否阅读了要提交的文档,或尝试使用此代码?
    • 无论如何,我已经添加了一种方法来区分按钮,因为它是正确的,你不能通过绑定提交来做到这一点。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 2020-10-16
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 2017-07-13
      相关资源
      最近更新 更多