假设您在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来做这个吗?


当前回答

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

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

其他回答

这是我尝试过的:

你需要确保你给你的按钮不同的名字 编写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();
}

用你给的例子:

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

如果您点击“上一页”,只会提交“prev”的值。如果你点击“下一页”,只有“下一页”的值会被提交。

但是,如果您在表单的某个地方按下Enter键,则“上一页”和“下一页”都不会提交。

所以使用伪代码你可以做到以下几点:

If "prev" submitted then
    Previous Page was click
Else If "next" submitted then
    Next Page was click
Else
    No button was click

给你的提交按钮设置相同的名称,就像这样:

<input type="submit" name="submitButton" value="Previous Page" />
<input type="submit" name="submitButton" value="Next Page" />

当用户按下Enter并将请求发送到服务器时,您可以在服务器端代码中检查submitButton的值,该代码包含一组表单名称/值对。例如,在ASP Classic中:

If Request.Form("submitButton") = "Previous Page" Then
    ' Code for the previous page
ElseIf Request.Form("submitButton") = "Next Page" Then
    ' Code for the next page
End If

参考:在一个表单上使用多个提交按钮

另一个简单的选项是将返回按钮放在HTML代码中的提交按钮之后,但将其浮动到左侧,这样它就会出现在提交按钮之前的页面上。

要做到这一点,只需改变制表符顺序即可。保持简单。

将之前的按钮类型更改为这样的按钮:

<input type="button" name="prev" value="Previous Page" />

现在Next按钮将是默认的,另外你也可以添加默认属性,这样你的浏览器就会高亮显示它:

<input type="submit" name="next" value="Next Page" default />