Hi,
I’m trying to add auto-complete functionality, but when I click one of the results, I can’t make it alert on the screen.
What am I missing?
<span id="box">
<input type="text" id="search_box">
<button id="search_button">Search</button>
</span>
<div id="search_result"></div>
PHP
$param = "%{$_POST['value']}%";
$stmt = $sqli->prepare("SELECT username FROM testtable2 WHERE username LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
echo "<a class='username'>$username</a><br>"; // There is no problem with PHP code, it echoes the results successfully.
}
JS
$(document).ready(function () {
var left = $('#box').position().left;
var top = $('#box').position().top;
var width = $('#box').width();
$('#search_result').css('left', left).css('top', top + 32).css('width', width);
$('#search_box').keyup(function () {
var value = $(this).val();
if (value != '') {
$('#search_result').show();
$.post(
'search.php',
{
value: value
}, function (data) {
$('#search_result').html(data);
});
} else {
$('#search_result').hide();
}
});
$(".username").click(function () {
var username = $(this).text();
alert(username); // It doesn't do anything, why?
});
});