从php / mysql自动完成中获取价值
问题描述:
I have some script to search city on table city from mysql database. Everything works but when the result displaying I would like when I click on result, display this on my input search. An idea to helping me ?
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>
答
You will need to output the individual cities in an element rather than just separated by <br>
's and then need to listen to delegated
events for the onclick
e.g.
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>';
Then in javascript you need to listen to delegated events as the elements aren't there from the beginning of the page load when the javascript is first interpreted. https://learn.jquery.com/events/event-delegation/
So you need to do something like this:
Javascript:
$(document).on("click", "li.search-city", function(){
// Now do whatever you want with the clicked value
console.log($(this).val());
});