Removing on keyup from jQuery search script
I have a jQuery search script which uses the on keyup function to submit the query. How can I make it search when the user presses enter?
Here is my current code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&page=1';
window.location.hash='search/'+query+'/1/';
document.title=$(this).val()+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#res开发者_开发知识库ult").html(response);
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
#search_form must be id of <form>
!
$(document).ready(function(){
$("#search_form").submit(function(){
var search=$("#search").val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&page=1';
window.location.hash='search/'+query+'/1/';
document.title=search+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
I have found that I need to do this, have 2 events, one that caters for the enter key and one that ignores the keypress:
jQuery('#search').keydown(function (e) {
if (e.which == 13) {
// Do you work here
}
});
jQuery('#search').keypress(function (e) {
if (e.which == 13) {
return false;
}
});
In general case
$(document).keyup(function( e ) {
if (e.keyCode == 13) {
// execute your code
}
});
精彩评论