-1

Thanks in advance for your attention,

I'm using the W3 PHP AJAX Live Search Example and it's already integrated on this site. It's just about perfect. I wish to use arrows on keyboard, up (or left) and down (or right), to focus results inside of <div id="livesearch">. Than, on focus press Enter ⏎ key to load.

Kanti
  • 627
  • 4
  • 18
Uncle Iroh
  • 376
  • 5
  • 17
  • 4
    may as well start with one that has it, than add to an existing one: https://jqueryui.com/autocomplete/. yes its a bad question (no code, no research, no attempt to answer it your self) we are not just here to right code for you. –  Nov 04 '16 at 02:26
  • After 15 minutes of searching, it seemed like all the demos and tutorials on the web have "slow loading" live search results. Thanks for the feedback and good luck @nogad or /u/nogad - I'll take your advice and move onwards...I can learn more from this post too http://stackoverflow.com/a/819780/1927168 – Uncle Iroh Nov 04 '16 at 02:36

2 Answers2

4

In HTML head :

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <style>
    #livesearch {
        min-height: 155px;
    }
    #livesearch a:hover {
        text-decoration: none;
        background-color: rgba(0,0,0,0.05);
    }
    #livesearch a {
        text-transform: capitalize;
        font-size: inherit;
        padding: 5px 13px;
        display: block;
    }
    #livesearch .selected {
        text-decoration: none;
        background-color: rgba(0,0,0,0.05);
    }
    </style>
</head>

HTML Form :

<body>
    <form method="post" id="myfrm">
        <input type="text" name="search" class="form-control search" placeholder="Just start typing..." autofocus="">
    </form>
    <div id="livesearch"><div>
</body>

AJAX function :

<script>
    function showResult(str) {
      if (str.length==0) { 
        document.getElementById("livesearch").innerHTML="";
        document.getElementById("livesearch").style.border="0px";
        return;
      }
      if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
      } else { 
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        if (this.readyState==4 && this.status==200) {
          document.getElementById("livesearch").innerHTML=this.responseText;
        }
      }
      xmlhttp.open("GET","livesearch.php?q="+str,true);
      xmlhttp.send();
    }
</script>

Jquery :

<script>
$(document).ready(function ($) {

    $('.search').keyup(function (e) {
        var key = e.keyCode;

        if (key == 40 || key == 38 || key == 13) {
           return false;
        }
        var str = $('.search').val();
        showResult(str);
    });

    $('#myfrm').on("keydown", ".search", function (e) {

        var $listItems = $('#livesearch a');
        var key = e.keyCode,
                $selected = $listItems.filter('.selected'),
                $current;

        if (key != 40 && key != 38 && key != 13)
            return;

        //$listItems.removeClass('selected');

        if (key == 40) // Down key
        {
            $listItems.removeClass('selected');
            if (!$selected.length || $selected.is(':last-child')) {
                $current = $listItems.eq(0);
            } else {
                $current = $selected.next();
            }
            console.log("Current : "+$current);
        } 
        else if (key == 38) // Up key
        {
            $listItems.removeClass('selected');
            if (!$selected.length || $selected.is(':first-child')) {
                $current = $listItems.last();
            } else {
                $current = $selected.prev();
            }
        } 
        else if (key == 13) // Enter key
        {
            $current = $listItems.filter('.selected');
            $current.trigger('click');
            return false;
        }
        $current.addClass('selected');
    });
});
</script>

Retrieve data in input search box from livesearch data :

<script>
$(document).ready(function ($) {
    $("body").on("click", "#livesearch a", function(e){
        e.preventDefault();
        var data = $(this).text();
        $(".search").val(data);
        $('#livesearch').html('');
    });
});
</script>

If you want used instead of ajax showResult(str) using ajax+jquery for data retrieve livesearch.php so, you can used bellow code :

<script>
$(document).ready(function ($) {
    $('.search').keyup(function (e) {

        var key = e.keyCode;

        if (key == 40 || key == 38 || key == 13) {
          return false;
        }
        var str = $('.search').val();
        $.ajax({
            context: this,
            url: 'livesearch.php',
            type: 'get',
            dataType: 'html',
            data: {
                q: str,
            },
            beforeSend: function () {
                console.log("Loadding...");
            }
        }).done(function (response) {
            $("#livesearch").html(response);
        });
    });
});
</script>
Razib Al Mamun
  • 2,663
  • 1
  • 16
  • 24
  • excellent feedback and thanks for the input. I added the coded, still playing around with things, it doesn't work but you can see the trigger being fired off, and the css working...if you wish, revisit page again - https://von.host/knowledgebase.php – Uncle Iroh Nov 13 '16 at 04:22
  • 1
    Hi, i revisit your site, i saw some problem, i have updated my answer as per last problem. Edited my answer in 2 function `$('.search').keyup(function (e) {` and `$("body").on("click", "#livesearch a", function(e){` – Razib Al Mamun Nov 14 '16 at 05:42
  • 1
    first function added `var key = e.keyCode; if (key == 40 || key == 38 || key == 13) { return false; }` and 2nd function added `$('#livesearch').html('');` Please follow and paste my code carefully. i have 100% worked now. – Razib Al Mamun Nov 14 '16 at 05:43
1
document.getElementById("yourtextfield").addEventListener("keyup",function(event){
    var livesearchelem = document.getElementById("livesearch");
    var childrens = livesearchelem.getElementsByTagName("a"); //Get only hyperlinks
    var key = event.keyCode;
    var selected = this.selectedResultNumber;
    if (key == 38){ //Arrow up
        if (childrens.length === 0){ return; }
        if (!selected){ //If 'selectedResultNumber' is undefined
            childrens[childrens.length - 1].style.backgroundColor = 'blue';
            childrens[childrens.length - 1].style.color = 'white';

            //Store the selected number into this element
            this.selectedResultNumber = childrens.length - 1;
        }
        else if (selected > 1){
            //Restore the previous selected element's style
            childrens[selected - 1].style.backgroundColor = 'white';
            childrens[selected - 1].style.color = 'black';

            //Set the new selected element's style
            childrens[selected - 2].style.backgroundColor = 'blue';
            childrens[selected - 2].style.color = 'white';

            //Decrease the selected number by 1
            this.selectedResultNumber--;
        }
    }
    else if (key == 40){ //Arrow down
        if (childrens.length === 0){ return; }
        if (!selected){ //If 'selectedResultNumber' is undefined
            childrens[0].style.backgroundColor = 'blue';
            childrens[0].style.color = 'white';

            //Store the selected number into this element
            this.selectedResultNumber = 1;
        }
        else if (selected < childrens.length){
            //Restore the previous selected element's style
            childrens[selected - 1].style.backgroundColor = 'white';
            childrens[selected - 1].style.color = 'black';

            //Set the new selected element's style
            childrens[selected].style.backgroundColor = 'blue';
            childrens[selected].style.color = 'white';

            //Increase the selected number by 1
            this.selectedResultNumber++;
        }
    }
    else if (key == 13){ //Enter key
        if (childrens.length === 0){ return; }
        //Trigger click event on the selected element
        childrens[selected - 1].click();
    }
    else{ //Searching in progress
        delete this.selectedResultNumber;

        //Your search function goes here
    }
});
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
  • thanks for the comments, very helpful. is your code above getting wrapped inside of a ` – Uncle Iroh Nov 13 '16 at 04:13
  • 1
    Yup you can wrap it inside a ` – Thum Choon Tat Nov 14 '16 at 02:14