2个提交按钮以操作不同的URL

问题描述:

需要jquery的帮助才能根据按下SUBMIT Button来更改我的表单操作. 我找到了一些JavaScript代码,但无法正常工作.

Need help with jquery to change my forms action depending on with SUBMIT Button press. I found some javascript code but its not working.

<form name="myform" onsubmit="return onsubmitform();">

这是功能

    <script type="text/javascript">
    function submitform()
    {
         if(document.pressed == 'Save')
         {
              document.myform.action ="jbupdate.php";
         } else
         if(document.pressed == 'Print')
         {
              document.myform.action ="ppage.php";
         }
         return true;
     }
     </script>

这些是我的提交按钮

     <input type="submit" name="operation" onclick="document.pressed=this.value" value="Save" />
     <input type="submit" name="operation" onclick="document.pressed=this.value" value="Print" />

我希望将这些信息发布到这些操作页面上,具体取决于所按下的按钮.

I will like to POST this information to these action pages depending on the button pressed.

如果您在JavaScript控制台中查看,则在尝试提交表单时会看到一条错误消息,该错误消息将告诉您大部分问题所在:在表单的submit处理程序中,您尝试调用一个名为onsubmitform的函数:

If you look in the JavaScript console, you'll see an error message when you try to submit the form that will tell you a big part of what's wrong: In your form's submit handler, you're trying to call a function called onsubmitform:

<form name="myform" onsubmit="return onsubmitform();">
<!--                                 ^--- here     -->

...但是您的函数实际上称为submitform:

...but your function is actually called submitform:

<script type="text/javascript">
function submitform()
//       ^--- here

如果您使这些名称匹配,尽管我不是完全肯定要确保这些名称匹配,但肯定希望在表单的submit处理程序之前触发提交按钮的click事件完全可靠的跨浏览器.

If you make those names match, it'll probably mostly work, although I'm not entirely sure expecting the submit button's click event to fire prior to the form's submit handler is entirely reliable cross-browser.

FWIW,但是,我可能会做不同的事情.既然您说您使用的是jQuery,我将完全放弃全局submitform函数,添加一个隐藏字段,并将按钮设置为按钮(而不是提交按钮),因为除非启用了JavaScript,否则您的表单已经无法正常使用

FWIW, though, I'd probably do it differently. Since you say you're using jQuery, I'd ditch the global submitform function entirely, add a hidden field, and make the buttons just buttons (rather than submit buttons) since your form is already non-functional unless JavaScript is enabled.

所以:

<input type="hidden" name="operation" value="" />
<input type="button" value="Save" />
<input type="button" value="Print" />

具有:

jQuery(function($) {
    var form = document.myform;
    $(form).find("input[type='button']").click(function() {
        form.operation = this.value;
        form.action = this.value == 'Save' ? 'jbupdate.php' : 'ppage.php';
        form.submit();
        return false;
    });
});