假设您在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来做这个吗?
用你给的例子:
<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
在大多数浏览器中,无需JavaScript或CSS即可工作:
<form>
<p><input type="text" name="field1" /></p>
<p><a href="previous.html">
<button type="button">Previous Page</button></a>
<button type="submit">Next Page</button></p>
</form>
Firefox, Opera, Safari和谷歌Chrome浏览器都可以使用。一如既往,ie浏览器是问题所在。
当JavaScript被打开时,这个版本可以工作:
<form>
<p><input type="text" name="field1" /></p>
<p><a href="previous.html">
<button type="button" onclick="window.location='previous.html'">Previous Page</button></a>
<button type="submit">Next Page</button></p>
</form>
所以这个解决方案的缺陷是:
如果您使用关闭JavaScript的Internet Explorer,“上一页”将无法工作。
请注意,后退按钮仍然有效!
有时palotasb提供的解决方案是不够的。有一些用例,例如“Filter”提交按钮被放置在“Next和Previous”按钮之上。我找到了一个解决办法:复制提交按钮,这需要作为默认提交按钮在一个隐藏的div,并把它放在任何其他提交按钮上面的表单。
从技术上讲,当按下Enter时,它将由不同的按钮提交,而不是单击可见的Next按钮。但是由于名称和值是相同的,所以结果没有区别。
<html>
<head>
<style>
div.defaultsubmitbutton {
display: none;
}
</style>
</head>
<body>
<form action="action" method="get">
<div class="defaultsubmitbutton">
<input type="submit" name="next" value="Next">
</div>
<p><input type="text" name="filter"><input type="submit" value="Filter"></p>
<p>Filtered results</p>
<input type="radio" name="choice" value="1">Filtered result 1
<input type="radio" name="choice" value="2">Filtered result 2
<input type="radio" name="choice" value="3">Filtered result 3
<div>
<input type="submit" name="prev" value="Prev">
<input type="submit" name="next" value="Next">
</div>
</form>
</body>
</html>
我认为这是一个简单的解决方法。将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>