I have a jQuery search script that queries a PHP file then parses the results into an HTML div. When no query is active the text box is automatically selected but when a query is active I want it not to be automatically selected. Currently I have only been able to disable the text box which isn’t what I want. How can I resolve this issue?
My jQuery 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',
beforeSend:function(){
$('#query').prop('disabled',true);
},
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();
}
$('#query').focus();
});
This is the ‘answer’ version of the comment I just made. If you use
$('#query').val().lengthyou can grab the length of the value in the textbox, like so:I don’t think the
.blur();is really required, but it can’t hurt either.edit #1: Okay, I assume you have a page where there is a search box and a
div-tag where your items are stored (which you do by AJaX). Also I assume that when you then hit F5 (thus reload the whole page) your page will reload and there will already be data in the search box (by PHP or earlier JavaScript statements). Then you can replace your current$('#query').focus();, with the code I posted above.edit #2: I’ve just re-read your code, and I think replacing
$('#query').focus();with my code should do the trick exactly like you want.