我在网站上创建了带有文本字段和按钮的搜索功能。我一直试图在输入时激活搜索,但它不起作用。我尝试了很多不同的方法,但似乎都没有。我已经读过这个按钮可能有问题而不是"默认"。我对此很新,所以任何帮助都非常感谢! 这是搜索按钮,返回按钮和搜索字段的脚本:
<div class="w3-top">
<div title="Clear"><a id="returnbtn" class="aa bb cc">
<i class="fa fa-eraser"></i>
</a></div>
<div title="Search"><a id="searchbtn" class="aa bb cc">
<i class="fa fa-search"></i>
</a>
<a class="aa bb cc">
<?php
$searchstr='';
$sql = "SELECT ID, ISBN, Author, Title, Publisher, ReleaseYear, Barcode FROM Books ";
$searchstr='';
if (isset($_GET['searchstr'])){
$searchstr=strtolower($_GET['searchstr']);
}
if($searchstr != ""){
$sql.="WHERE LOWER(Author) LIKE '%".$searchstr."%' OR LOWER(Title) LIKE '%".$searchstr."%' OR LOWER(Publisher) LIKE '%".$searchstr."%'";
}
echo "<form id='search'>";
echo "<input id='searchfield'/ value='".$searchstr."' autocomplete='off'>";
echo "</form>";
?>
</a>
</div>
</div>
这是搜索按钮功能
$(document).ready(function(){
$("#searchbtn").on('click', function(){
var newLink = UpdateCurrentLink('searchstr', $("#searchfield").val(), null);
newLink = UpdateCurrentLink('page', 1, newLink);
window.location = newLink;
});
$("#searchfield").keypress(function(e){
if(e.which === 13){//Enter key pressed
$('#searchbtn').click();//Trigger search button click event
}
});
答案 0 :(得分:1)
抓住每个人的按键并检查按下的键是否为 Enter : 试试这个:
$(document).ready(function(){
$("body").keypress(function(e){
if (e.which === 13){
alert('Keypress');
$('#searchbtn').click();
e.preventDefault();
return false;
}
});
});
答案 1 :(得分:0)
$(&#34; searchbtn&#34;)。click()函数不会触发click事件。你必须使用触发方法。您可以尝试这样 -
$(document).ready(function(){
$("#searchField").on('keypress', function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//console.log('enter press');
$("#searchBtn").trigger('click')
}
})
$("#searchBtn").on('click', function(e){
e.preventDefault();
console.log("on submit clicked");
})
})
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<body>
<form>
<input id="searchField" value=""/>
</form>
<p> <a href="#" id="searchBtn"> Search </a> </p>
</body>
</html>
&#13;