2017-04-20 87 views
1

我正在构建一个AJAX实时搜索,它的工作原理,但我想使用键盘箭头(上/下)导航。我不知道我该怎么做。添加箭头导航到Ajax实时搜索

我form.php的

<div class="input-group" id="nav-input-group" style="display:table;"> 
    <input name="q" id="thesearchbar" class="form-control input-search " name="search" placeholder="Serach..." autocomplete="off" type="text" onclick=""> 
    <div class="result"></div> 
</div> 

我的脚本

$(document).ready(function(){ 
    $('#nav-input-group input[type="text"]').on("keyup input", function(){ 
     /* Get input value on change */ 
     var inputVal = $(this).val(); 
     var resultDropdown = $(this).siblings(".result"); 
     if(inputVal.length){ 
      $.get("_ajax_search.php", {term: inputVal}).done(function(data){ 
       // Display the returned data in browser 
       resultDropdown.html(data); 
      }); 
     } else{ 
      resultDropdown.empty(); 
     } 
    }); 
    // Set search input value on click of result item 
    $(document).on("click", ".result p", function(){ 
     $(this).parents("#nav-input-group").find('input[type="text"]').val($(this).text()); 
     $(this).parent(".result").empty(); 
    }); 
}); 

和_ajax_search.php

<?php 
require('bdd_pdo_connect.php'); 
try{ 
    if(isset($_REQUEST['term'])){ 
     $sql = "SELECT * FROM subcategories WHERE subcategory LIKE :term"; 
     $stmt = $bdd->prepare($sql); 
     $term = '%' . $_REQUEST['term'] . '%'; 
     $stmt->bindParam(':term', $term); 
     $stmt->execute(); 
     if($stmt->rowCount() > 0){ 
      while($row = $stmt->fetch()){ 
       echo "<p>" . $row['subcategory'] . "</p>"; 
      } 
     } else{ 
      echo "<p>No matches found"; 
     } 
    } 
} catch(PDOException $e){ 
    die("ERROR: Could not able to execute $sql. " . $e->getMessage()); 
} 
unset($bdd); 
?> 

我是新的AJAX和任何帮助将不胜感激。

+0

我看不到你的代码中的任何AJAX调用... – Hulothe

+0

哪里是在你的代码Ajax调用? –

+0

对不起,我只是更新我的文章 – Rubyx

回答

1

为什么不使用HTML select标记做出下拉列表?它默认支持箭头键导航。如果要显示所有选项,请使用HTML select标记的size属性(请参阅HTML5 size attribute specification)。

HTML

<div class="input-group" id="nav-input-group" style="display:table;"> 
    <input name="q" id="thesearchbar" class="form-control input-search " name="search" placeholder="Serach..." autocomplete="off" type="text" onclick=""> 
    <select class="result" size="10"></div> <!-- size="10" is an example here --> 
</div> 

JS

// (ajax part) 
// ... 

$(document).on("change", ".result", function(){ 
    $(this).parents("#nav-input-group").find('input[type="text"]').val($(this).val()); 
    $(this).empty(); 
});