我在页面上有四个表单,我希望根据按下的箭头键提交其中任何一个表单。
<form name='go_north' action='' method='post'>
<input type='hidden' name='direction' value='north' />
</form>
<form name='go_east' action='' method='post'>
<input type='hidden' name='direction' value='east' />
</form>
etc...
如果他们有焦点,我可以看看如何使用文本输入,但我无法弄清楚如何使用隐藏的输入来完成它。此外,它只需要在Chrome中工作。任何建议都将不胜感激。
答案 0 :(得分:1)
添加一个document.addEventListener("keydown", function(){})
来监听按键,然后确定键码并映射它们以根据键码提交表单。
提交表单就像找到表单并在其上调用.submit()
一样简单!
document.addEventListener("keydown", function(event) {
var code;
if (event.key !== undefined) {
code = event.key;
} else if (event.keyIdentifier !== undefined) {
code = event.keyIdentifier;
} else if (event.keyCode !== undefined) {
code = event.keyCode;
}
console.log(code);
handleArrow(code);
});
function handleArrow(code) {
switch (code) {
case 'ArrowLeft':
submitForm('go_west');
break;
case 'ArrowRight':
submitForm('go_east');
break;
case 'ArrowDown':
submitForm('go_south');
break;
case 'ArrowUp':
submitForm('go_north');
break;
}
}
function submitForm(id) {
$("#" + id).submit();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="go_north">
<label for="north">north</label>
<input id="north" type="text" name="north" value="north">
</form>
<form id="go_east">
<label for="east">east</label>
<input id="east" type="text" name="east" value="east">
</form>
<form id="go_south">
<label for="south">south</label>
<input id="south" type="text" name="south" value="south">
</form>
<form id="go_west">
<label for="west">west</label>
<input id="west" type="text" name="west" value="west">
</form>