I trying to create a auto-complete search script (jQuery + PHP) but I have a big problem with this script.
My jQuery code is:
$(document).ready(function() {
$("#search").keyup(function() {
var search = $("#search").val();
if (search.length > 0) {
$.ajax({
type: "POST",
url: "search.php",
data: "q="+search,
dataType: "text",
cache: false,
success: function(result){
$("#autocomplete").fadeIn("fast");
$("#autocomplete").html(result);
}
});
}
});
$("#autocomplete").click(function() {
var complete = $(this).attr("title");
alert(complete);
$("#search").focus();
});
});
PHP code:
<?php
include("config.php");
header("Content-type: text/html; charset=UTF-8");
$search = $_POST['q'];
if(mb_strlen($search, "UTF-8") > 0) {
$query = "SELECT * FROM `search` WHERE `title` LIKE '%$search%' ORDER BY `title` ASC";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
if($num == 0) {
echo "Няма резултати";
}
else {
while ($row = mysql_fetch_assoc($result)) {
echo "<a href=\"javascript:void(0)\" class=\"link\" title=\"{$row['title']}\">{$row['title']}</a> <br />";
}
}
}
?>
but error is in jQuery cuz it can’t to get attr("title") of links…
Please help and sorry for my English 🙂
Since your links are dynamic, you’ll need to use the
.livemethod. You also want to target the individual links and not the container (I assumeautocompleteis the container for your.linkanchors).