2015-05-29 86 views
0

我有一些腳本從mysql數據庫中搜索城市表城。 一切正常,但當結果顯示時,我想單擊結果時,將其顯示在我的輸入搜索中。 幫助我的想法?從php/mysql獲取值自動完成

JQUERY

<script type='text/javascript'> 
$(document).ready(function() { 
    $("#search_results").slideUp(); 
    $("#button_find").click(function(event) { 
     event.preventDefault(); 
     search_ajax_way(); 
    }); 
    $("#search_query").keyup(function(event) { 
     event.preventDefault(); 
     search_ajax_way(); 
    }); 

}); 

function search_ajax_way() { 
    $("#search_results").show(); 
    var search_this = $("#search_query").val(); 
    $.post("mod/search.php", { 
     searchit: search_this 
    }, function(data) { 
     $("#display_result").html(data); 

    }) 
} 
</script> 

PHP

$term = strip_tags(substr($_POST['searchit'], 0, 100)); 
$term = utf8_decode($term); 
$term = mysql_escape_string($term); // Attack Prevention 
$query = mysql_query("select distinct city from city where (city like '{$term}%') order by city limit 10 "); 

if (mysql_num_rows($query)) { 
    while ($row = mysql_fetch_assoc($query)) { 
     echo ''.utf8_encode($row['city']). 
     '<BR>'; 

    } 
} else { 
    echo 'No result'; 
} 

HTML

<input type="text" style="width:60%;margin-right:10px;" name="search_query" id="search_query" value="" autocomplete="off"> 
<div id="display_result"></div> 
+0

您可以用'typeahead' –

回答

1

您將需要輸出中的一個元素的各個城市,而不是僅僅通過<br>的分離,然後需要聽delegated事件爲onclick

例如

PHP:

echo "<ul>"; 
if (mysql_num_rows($query)) { 
    while ($row = mysql_fetch_assoc($query)) { 
     echo '<li class="search-city">'.utf8_encode($row['city']). 
     '</li>'; 

    } 
} else { 
    echo '<li>No result</li>'; 
} 

echo '</ul>'; 

然後在JavaScript中,你需要聽委派事件的元素不存在從頁面加載的開始時,JavaScript是第一個解釋。 https://learn.jquery.com/events/event-delegation/

所以,你需要做這樣的事情:

的Javascript:

$(document).on("click", "li.search-city", function(){ 
    // Now do whatever you want with the clicked value 
    console.log($(this).val()); 
});