Javascript HTML表单中键盘友好的AJAX搜索
我有一个类似这样的表单:Javascript HTML表单中键盘友好的AJAX搜索,javascript,php,jquery,ajax,keyboard-events,Javascript,Php,Jquery,Ajax,Keyboard Events,我有一个类似这样的表单: <form action="whatever.php" method="post"> <input type="text" onKeyUp="ajax_search()" name="search" id="search"> // THE AJAX FUNCTION UPDATES THE DIV BELOW <div id="search_results"></div> <in
<form action="whatever.php" method="post">
<input type="text" onKeyUp="ajax_search()" name="search" id="search">
// THE AJAX FUNCTION UPDATES THE DIV BELOW
<div id="search_results"></div>
<input type="text" name="price" id="price">
<input type="text" name="cost" id="cost">
<input type="text" name="discount" id="discount">
<input type="submit" value="GO">
</form>
$("#search").on("keyup", function(e) {
if(e.charCode === 38) { // Up arrow
e.preventDefault(); // Prevent the default action
currentSelection++; // Update the current selection
} else if(e.charCode === 40) { // Down Arrow
// ...etc....
}
});
单击
标记时,
将使用项目($code
)及其所有相关信息更新。这太棒了
我现在希望在AJAX
搜索中添加键盘功能。用户应该能够使用键盘箭头“选择”项目
我在这里读到了类似的讨论:
讨论并没有走得太远,最终的结果是代码对OP不起作用
此外,由于搜索结果
div已在
中显示,且
已聚焦,因此“回车”键将激活提交
按钮,而不是调用插入项()
功能。我可以使用javascript
if()
语句和ASCII代码自己解决这个问题
请帮助我使用键盘箭头键选择搜索的项目
更新
我已尝试为选中的
项目设置
标签,用于选项卡选择。但是当我点击选项卡时,所发生的一切就是
中的下一个
被聚焦。我会在一个if语句中捕获字符码,类似这样:
<form action="whatever.php" method="post">
<input type="text" onKeyUp="ajax_search()" name="search" id="search">
// THE AJAX FUNCTION UPDATES THE DIV BELOW
<div id="search_results"></div>
<input type="text" name="price" id="price">
<input type="text" name="cost" id="cost">
<input type="text" name="discount" id="discount">
<input type="submit" value="GO">
</form>
$("#search").on("keyup", function(e) {
if(e.charCode === 38) { // Up arrow
e.preventDefault(); // Prevent the default action
currentSelection++; // Update the current selection
} else if(e.charCode === 40) { // Down Arrow
// ...etc....
}
});
这里有一个非常有用的字符码列表
您应该能够以这种方式捕捉任何键(tab、enter、箭头等),并使用e.preventDefault()阻止它们的操作