开发者

Text box on page load automatically selected with jQuery

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜