假设您在HTML表单中创建了一个向导。一个按钮后退,一个按钮前进。因为当您按Enter键时,返回按钮首先出现在标记中,它将使用该按钮提交表单。

例子:

< >形式 <!—将光标移至该字段,按“Enter”。—> <input type="text" name="field1" /> <!这是提交的按钮——> <input type="submit" name="prev" value="Previous Page" /> <!——但这是我想提交的按钮——> <input type="submit" name="next" value=" next Page" /> > < /形式

我想要确定当用户按Enter键时使用哪个按钮提交表单。这样,当您按下Enter键时,向导将移动到下一页,而不是上一页。你必须使用tabindex来做这个吗?


当前回答

从https://html.spec.whatwg.org/multipage/forms.html implicit-submission

表单元素的默认按钮是树中的第一个提交按钮 它的表单所有者是该表单元素。 如果用户代理支持让用户隐式提交表单 (例如,在某些平台上,在输入文本时按下“enter”键 字段被隐式聚焦提交表单)…

将下一个输入设置为type="submit",并将前一个输入更改为type="button",应该会得到所需的默认行为。

<form>
   <input type="text" name="field1" /> <!-- put your cursor in this field and press Enter -->

   <input type="button" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
   <input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

其他回答

纯HTML无法做到这一点。要做到这一点,必须依赖JavaScript。

但是,如果在HTML页面上放置两个表单,则可以做到这一点。

Form1将拥有前面的按钮。

Form2将有任何用户输入+下一个按钮。

当用户在Form2中按下Enter键时,Next提交按钮将触发。

你可以用CSS来做。

首先在标记中放入Next按钮,然后是Prev按钮。

然后使用CSS来定位它们以显示您想要的方式。

这是我尝试过的:

你需要确保你给你的按钮不同的名字 编写if语句,在单击任意一个按钮时执行所需的操作。

 

<form>
    <input type="text" name="field1" /> <!-- Put your cursor in this field and press Enter -->

    <input type="submit" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
    <input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

在PHP中,

if(isset($_POST['prev']))
{
    header("Location: previous.html");
    die();
}

if(isset($_POST['next']))
{
    header("Location: next.html");
    die();
}

我认为这是一个简单的解决方法。将Previous按钮类型更改为button,并添加一个新的onclick属性,值为jQuery(this).attr('type','submit');

因此,当用户单击Previous按钮时,它的类型将被更改为submit,表单将与Previous按钮一起提交。

<form>
  <!-- Put your cursor in this field and press Enter -->
  <input type="text" name="field1" />

  <!-- This is the button that will submit -->
  <input type="button" onclick="jQuery(this).attr('type','submit');" name="prev" value="Previous Page" />

  <!-- But this is the button that I WANT to submit -->
  <input type="submit" name="next" value="Next Page" />
</form>

如果你真的只是想让它像安装对话框一样工作,只需要关注“Next”按钮OnLoad。

这样,如果用户点击Return,表单就会提交并继续。如果他们想返回,他们可以按Tab键或点击按钮。