最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - facebook like ajax search - how to go through results using the keyboard - Stack Overflow

programmeradmin1浏览0评论

Im trying to implement a facebook like search that will return results while the user is typing (autoplete), here is the jquery code I am using :

$(document).ready(function(){
    $("#searchField").keyup(function() 
    {
        var searchbox = $(this).val();
            if(searchbox=='')
            {
            $("#searchDisplay").html('').hide();
            }
            else
            {
                $.ajax({
                url: "ajax/?do=search_users&q="+ searchbox+"",
                //data: dataString,
                cache: false,
                    success: function(html)
                    {
                        $("#searchDisplay").html(html).show();
                    }
                });
            }return false;    
    });
});

$("#searchField").focusout(function(){
    $("#searchDisplay").slideUp();
});

$("#searchField").focus(function(){
    if($("#searchDisplay").html() != ''){
        $("#searchDisplay").slideDown();
    }
});

The returning result is in div structure. What I dont know how to do is to allow users to go through the results using the [UP] and [DOWN] keys on the keyboard and choosing the result by pressing the [ENTER] button.

EXTRA INFO

here is the display_box :

<div id="searchDisplay">
                echo '<a href="'.$_config['http'].$username.'"><div class="display_box" align="left">';
                echo '<img src="'.$img.'"  style="width:25px; float:left; margin-right:6px" />';
                echo $name.'<br/>';
                echo '<span style="font-size:9px; color:#999999">'.$username.'</span></div></a>';
</div>

THE HTML MARKUP

    <a href="ahoora"><div class="display_box" align="left">
    <img src=".jpg" style="width:25px; float:left; margin-right:6px">
<strong>a</strong>hour<strong>a</strong><br>
<span style="font-size:9px; color:#999999"><strong>a</strong>hoor<strong>a</strong></span>
</div></a>

each result has the above html code, and they are all loaded into a <div> with the id=searchDisplay.

*note that the php echo part has a while loop, the above code is just the idea of how the html is like (the searchDisplay is not in the same page as the result, check the jquery code).

Im trying to implement a facebook like search that will return results while the user is typing (autoplete), here is the jquery code I am using :

$(document).ready(function(){
    $("#searchField").keyup(function() 
    {
        var searchbox = $(this).val();
            if(searchbox=='')
            {
            $("#searchDisplay").html('').hide();
            }
            else
            {
                $.ajax({
                url: "ajax/?do=search_users&q="+ searchbox+"",
                //data: dataString,
                cache: false,
                    success: function(html)
                    {
                        $("#searchDisplay").html(html).show();
                    }
                });
            }return false;    
    });
});

$("#searchField").focusout(function(){
    $("#searchDisplay").slideUp();
});

$("#searchField").focus(function(){
    if($("#searchDisplay").html() != ''){
        $("#searchDisplay").slideDown();
    }
});

The returning result is in div structure. What I dont know how to do is to allow users to go through the results using the [UP] and [DOWN] keys on the keyboard and choosing the result by pressing the [ENTER] button.

EXTRA INFO

here is the display_box :

<div id="searchDisplay">
                echo '<a href="'.$_config['http'].$username.'"><div class="display_box" align="left">';
                echo '<img src="'.$img.'"  style="width:25px; float:left; margin-right:6px" />';
                echo $name.'<br/>';
                echo '<span style="font-size:9px; color:#999999">'.$username.'</span></div></a>';
</div>

THE HTML MARKUP

    <a href="ahoora"><div class="display_box" align="left">
    <img src="http://domain./upload/thumbs/ahoora_1336145552.jpg" style="width:25px; float:left; margin-right:6px">
<strong>a</strong>hour<strong>a</strong><br>
<span style="font-size:9px; color:#999999"><strong>a</strong>hoor<strong>a</strong></span>
</div></a>

each result has the above html code, and they are all loaded into a <div> with the id=searchDisplay.

*note that the php echo part has a while loop, the above code is just the idea of how the html is like (the searchDisplay is not in the same page as the result, check the jquery code).

Share Improve this question edited May 7, 2012 at 0:13 Ahoura Ghotbi asked May 1, 2012 at 8:54 Ahoura GhotbiAhoura Ghotbi 2,89614 gold badges38 silver badges65 bronze badges 4
  • Can you please show the HTML for #searchDisplay? – Jivings Commented May 1, 2012 at 10:01
  • I added it to the main question – Ahoura Ghotbi Commented May 1, 2012 at 10:53
  • hey, you are showing the php code for that, but it's a bit confusing, not that i can't read php, but it's bloated with lot's of variables not shown here. So, can you please show an example of the generated markup - devoid of php? that'd be helpful in solving the question. – Parth Thakkar Commented May 6, 2012 at 16:33
  • I have posted just the html without the php codes inside – Ahoura Ghotbi Commented May 7, 2012 at 0:13
Add a ment  | 

5 Answers 5

Reset to default 4 +25

There is a jQuery plugin which allows to to bind action to keyboard shortcurs. I've used it to navigate a list of items using cursor keys:

https://github./jeresig/jquery.hotkeys

Defining a shortcut key with plugin is as simple as that:

$(document).bind('keydown', 'ctrl+a', fn);

jQuery UI autoplete handles this functionality nicely, without any additional code:

http://jqueryui./demos/autoplete/

See the demo at this url for a quick primer.

Try this code... i have found from my bookmarks collection

http://www.9lessons.info/2009/06/autosuggestion-with-jquery-ajax-and-php.html

I've rewritten your code a little bit, should do the same, just easier to read and a little more efficient:

$("#searchField").on({
    keyup : function(e) {
        var code = (e.keyCode ? e.keyCode : e.which),
            searchbox = this.value,
            Sdisplay = $("#searchDisplay");
        if(searchbox=='') {
            Sdisplay.html('').hide();
        }else{
           $.ajax({
            url: "ajax/?do=search_users&q="+ searchbox+"",
            //data: dataString,
            cache: false
           }).done(function(html) {
               Sdisplay.html(html).show();
           });
        }
    },
    focus: function() {
        $("#searchDisplay").slideDown();        
    },
    blur: function() {
        $("#searchDisplay").slideUp();
    }
});

As for the search results, you could either just target each <a> element, but chances are you have other <a> elements on your site, so I would add a wrapper to make them easier to target, you could do that with jQuery's wrap() and each() functions, but if possible the easiest would be to just add it in your PHP, like so:

<div id="searchDisplay">
    echo '<div class="wrapper">';
    echo '<a href="'.$_config['http'].$username.'">';
    echo '<div class="display_box" align="left">';
    echo '<img src="'.$img.'" style="width:25px; float:left; margin-right:6px" />';
    echo $name.'<br/>';
    echo '<span style="font-size:9px; color:#999999">'.$username.'</span></div></a>';
    echo '</div>';
</div>

As for toggling the result with the up / down arrow keys and changing location to the search results, I would do something like (notice the use of the .wrapper class added previously) :

if (code == 40 || code == 38 || code == 13) {//arrow keys and enter
    if ($("#searchDisplay").is(':visible')) {
        switch (code) {
            case 40: //arrow down
               act = act > $('.wrapper').length-2 ? 0 : act+1;
               $(".wrapper").removeClass('active').eq(act).addClass('active');
            break;
            case 38: //arrow up
               act = act < 1 ? $('.wrapper').length-1 : act-1;
               $(".wrapper").removeClass('active').eq(act).addClass('active');
            break;
            case 13: //enter key
               var ViElms = $('.wrapper').filter(':visible').filter('.active').length;
               if (ViElms) { //if there are any search results visible with the active class
                   var link = $('.wrapper').eq(act).find('a')[0].href;
                   window.location.href = link;
               }
           break;
     }
}

Now to cache some selectors, and put it together with the keyup function, do :

$(document).ready(function() {
    var act = -1;
    $("#searchField").on({
        keyup: function(e) {
            var code = (e.keyCode ? e.keyCode : e.which),
                searchbox = this.value,
                Sdisplay = $("#searchDisplay"),
                wrappers = $('.wrapper'); //there's that class again
            if (searchbox == '') {
                Sdisplay.html('').hide();
            } else {
                Sdisplay.show();
                if (code == 40 || code == 38 || code == 13) { //do not search on arrow keys and enter
                    if (Sdisplay.is(':visible')) {
                        switch (code) {
                        case 40: //arrow down
                            act = act > wrappers.length - 2 ? 0 : act + 1;
                            wrappers.removeClass('active').eq(act).addClass('active');
                            break;
                        case 38: //arrow up
                            act = act < 1 ? wrappers.length - 1 : act - 1;
                            wrappers.removeClass('active').eq(act).addClass('active');
                            break;
                        case 13: //enter
                            var ViElms = wrappers.filter(':visible').filter('.active').length;
                            if (ViElms) { //if there are any search results visible with the active class
                               var link = wrappers.eq(act).find('a')[0].href;
                               window.location.href = link;
                            }
                            break;
                        }
                    }
                } else { //do search
                    $.ajax({
                       url: "ajax/?do=search_users&q="+ searchbox+"",
                       //data: dataString,
                       cache: false
                    }).done(function(html) {
                       Sdisplay.html(html).show();
                    });
                }
            }
        },
        focus: function() {
            $("#searchDisplay").slideDown();
        },
        blur: function() {
            $("#searchDisplay").slideUp();
        }
    });
});​

Here's a DEMONSTRATION

Try this. Scrolls through the list and es back around to the top/bottom when you go past the beginning/end.

<script type="text/javascript">
<!--
$(document).ready(function() {
    $("#searchbox").on("keydown",handleKeys);
});
function handleKeys(e) {

    var keyCode=e.keyCode? e.keyCode : e.charCode;
    if (keyCode==40 && $("a.activeoption").length==0) {
        $("a").eq(0).addClass("activeoption");
    } else if (keyCode==40 && $("a.activeoption").length!=0) {
        $("a.activeoption").next().addClass("activeoption");
        $("a.activeoption").eq(0).removeClass("activeoption");
        if ($("a.activeoption").length==0)
            $("a").eq(0).addClass("activeoption");
    } else if (keyCode==38 && $("a.activeoption").length==0) {
        $("a").last().addClass("activeoption");
    } else if (keyCode==38 && $("a.activeoption").length!=0) {
        var toSelect=$("a.activeoption").prev("a");
        $("a.activeoption").eq(0).removeClass("activeoption");
        toSelect.addClass("activeoption");
        if ($("a.activeoption").length==0)
            $("a").last().addClass("activeoption");
    } else if (keyCode==13) {
        window.location=$("a.activeoption")[0].href;
    }
}
//-->
</script>

Demo: http://www.dstrout/pub/keyscroll.htm

发布评论

评论列表(0)

  1. 暂无评论