Live search results clickable using ajax?

I am able to search and display the results that the user is typing on the keyup function. But now when the results show up inside my tag, they are not clickable. Is there a way I can make them clickable and also allow the user to select multiple results from the live search results. Please help me out. This is what I tried so far.

html

<input type="text" id ="medication" name="medication" onkeyup="getsearch(this.value)"><br>
<div id="livesearch"></div>

JavaScript

function getsearch(val) {
  results = [];
  document.getElementById("livesearch").innerHTML = "";

  if (val.length == 0) {
    document.getElementById("livesearch").innerHTML = "";
    document.getElementById("livesearch").style.border = "0px";
    return;
  }
  console.log(s);
  console.log("val", val);
  if (val.length > 2) {
    for (var i = 0; i < s.length; i++) {
      for (key in s[i]) {
        if (s[i][key].indexOf(val) != -1) {

          $("#livesearch").append(s[i][key]);
          $("#livesearch").append("<br/>");
          results.push(s[i]);
        }
      }
    }
  }
  console.log(results);
};

1 answer

  • answered 2018-02-13 02:17 andre mcgruder

    There are some other thing I would do differently here, but as far as what you are looking to do this should work.

    if(val.length>2) {
             for (var i = 0; i < s.length; i++) {
                 for (key in s[i]) {
                     if (s[i][key].indexOf(val) != -1) {
                         var newDom = $('<div><\div>'); //create a DOM element to wrap each of the return  text in.
    
                         newDom.text(s[i][key]); 
    
                         $("#livesearch").append(newDom);
    
                         results.push(s[i]);
                     }
                 }
             }
         }
    

    Then you can assign the click event to you dynamically created DOM this way.

    $('#livesearch').on('click', 'div', myDoStuffFunc);
    
     function myDoStuffFunc(){
         // this is fired from the click event
     }