【问题标题】:Submit button used out of the form表单外使用的提交按钮
【发布时间】:2013-03-24 16:05:22
【问题描述】:

我可以在表单之外使用提交按钮,并且仍然在单击提交按钮时处理表单操作吗?下面是代码。我是编程新手。请帮我。

<body>
<input type="submit" name="submit" value="submit" />
<form action="" method="get" name="myform">
  <table width="200" border="1" cellspacing="10">
    <tr>
      <td>Name</td>
      <td><label for="name"></label>
      <input type="text" name="name" id="name" /></td>
    </tr>
    <tr>
      <td>email</td>
      <td><label for="email"></label>
      <input type="text" name="email" id="email" /></td>
    </tr>
    <tr>
      <td>Group</td>
      <td><input type="checkbox" name="IT" id="IT" />
        IT 
          <input type="checkbox" name="ECE" id="ECE" />
        <label for="ECE"></label>
        ECE
        <input type="checkbox" name="Mech" id="Mech" />
        <label for="Mech"></label>
        Mech</td>
    </tr>
    <tr>
      <td>Hobbies</td>
      <td><label for="hobbies"></label>
      <input type="text" name="hobbies" id="hobbies" /></td>
    </tr>
  </table>
</form>
</body>

【问题讨论】:

  • 为什么不把按钮放在表单里面呢?你能告诉我们你的目标是什么吗?

标签: jquery html css forms html-table


【解决方案1】:

您可以使用 HTML5、纯 JavaScript 或 jQuery 来实现:

使用 JavaScript:

<form action="" method="get" id="theForm">
// Form here
</form>

<input type="submit" onclick="document.forms[0].submit();" />

使用 jQuery:

<form action="" method="get" id="theForm">
// Form here
</form>

<input type="submit" id="submitTheForm" />

$('#submitTheForm').click(function(){
    $('#theForm').submit();
});

使用 CSS(如果您出于美观原因只希望在表单之外使用它):

一个更好的选择可能是将您的提交留在表单内,并使用 CSS 将其放置在其他位置(如果这是您希望它在表单外的原因)。

使用 HTML5:

最后,您应该考虑使用 HTML5 的 form attributes。请注意,所有主要浏览器(Chrome、Firefox、IE10)都支持它们,但旧版本的 IE(IE9、IE8 等)不支持。这也应该有效:

<form id="something" method="post"> 
<input type="text"/> 
</form> 

<input type="submit" form="something">

【讨论】:

  • 只是好奇:新的 HTML5 属性“form”怎么样。 IE。
    我知道这适用于现代浏览器,但我'从未在表单外使用提交按钮进行测试。
  • @MiljanPuzović 我不知道 IE 是否支持?
  • 也许在 IE10 上,但 OP 没有提到浏览器支持,所以更新答案可能很好(嗯,这是另一种方法,所以......)。当然,请注意浏览器支持。
  • @MiljanPuzović 当然,我会在答案中更新它。我渴望 IE9 及之前版本被提炼成历史的那一天 :D
  • 感谢您的回答 +1 :)
【解决方案2】:

是的,你可以使用 jQuery 来做到这一点

<a href="#" id="submit-form">Submit</a>
<form id="someid">

</form>

jQuery:

$("#submit-form").click(function(){
$("#someid").trigger("submit");
})

【讨论】:

    【解决方案3】:

    使用 JQuery :

    <form action="" method="get" name="myform" id="myform">
    ...
    </form>
    
    <input type="button" id="submitform" value="click me to submit the form" />
    
    $('#submitform').click(function(){
        $('#myform').submit();
    });
    

    【讨论】:

      【解决方案4】:

      您必须使用一些 javascript 来实现这一点。这是一个例子

      <input type="button" onclick="document.forms['myform'].submit()" value="Submit" />
      

      【讨论】:

      • 感谢您的解决方案:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2018-07-03
      • 2011-10-24
      • 2013-08-06
      • 1970-01-01
      相关资源
      最近更新 更多