I have a jQuery search script that parses results from a PHP file into an HTML div. I want the search box to be selected automatically when there is no query active and for it not to be selected when there is a query active. How can I do this? I hope you can understand my question.
My jQuery search script is:
$(document).ready(function(){
$('[id^=type_]').click(function(){
type=this.id.replace('type_','');
$('[id^=type_]').removeClass('selected');
$('#type_'+type).addClass('selected');
return false;
});
$('#type_search').click();
$('#query').keyup(function(){
var query=$(this).val();
var url='/'+type+'/'+query+'/';
window.location.hash=''+type+'/'+query+'/';
document.title=$(this).val()+' - My Search';
$('#results').show();
if(query==''){
window.location.hash='';
document.title='My Search';
$('#results').hide();
}
$.ajax({
type:'GET',
url:url,
dataType:'html',
success:function(results){
$('#results').html(results);
}
});
});
if(window.location.hash.indexOf('#'+type+'/')==0){
query=window.location.hash.replace('#'+type+'/','').replace('/','');
$('#query').val(decodeURIComponent(query)).keyup();
}
});
This ajax edit will properly disable and enable/focus your #query field during the query
$.ajax({
type:'GET',
url:url,
dataType:'html',
beforeSend:function(){
$('#query').prop('disabled',true);
},
success:function(results){
$('#results').html(results);
$('#query').prop('disabled',false).focus();
}
});
EDIT: Add this to the bottom (inside) of your $(document).ready
function per your comment request:
if($('#results').html() == '')
{
$('#query').focus();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.