I have a Google Instant style jQuery script that displays search results as the user types in the search box. However, I want my script to make the user press enter the first time they want to submit a query but then after that for the instant search script to work.
How can I do this with the code I have posted below? I hope you can understand my question.
$('input').keyup(function(){
query=$(this).val();
url='/'+type+'/'+query+'/';
window.location.hash=开发者_如何学编程''+type+'/'+query+'/';
document.title=$(this).val()+' - My Search Script';
$('#results').show();
if(query==''){
window.location.hash='';
document.title='My Search Script';
$('#results').hide();
}
$.ajax({
type:'GET',
url:url,
dataType:'html',
success:function(results) {
$('#results').html(results);
}
});
});
var pressed = false;
$('input').keyup(function(event){
if (event.keyCode == '13' || pressed)
{
pressed = true;
query=$(this).val();
url='/'+type+'/'+query+'/';
window.location.hash=''+type+'/'+query+'/';
document.title=$(this).val()+' - My Search Script';
$('#results').show();
if(query==''){
window.location.hash='';
document.title='My Search Script';
$('#results').hide();
}
$.ajax({
type:'GET',
url:url,
dataType:'html',
success:function(results) {
$('#results').html(results);
}
});
}
});
this will only work for enter key
While the user has not pressed enter, the script will do nothing. Once the user presses enter, this will start to update the search each time a key is pressed:
var hasPressedEnter = false;
$('input').keyup(function(event){
if (event.keyCode == 13 /* ENTER */) {
hasPressedEnter = true;
}
if (!hasPressedEnter) {
return;
}
// rest of the code here
精彩评论