jQuery $(this).text() strange issue


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>
<div id="search_result"></div>


$param = "%{$_POST['value']}%";
$stmt = $sqli->prepare("SELECT username FROM testtable2 WHERE username LIKE ?");
$stmt->bind_param("s", $param);

while ($stmt->fetch()) {
    echo "<a class='username'>$username</a><br>"; // There is no problem with PHP code, it echoes the results successfully.


$(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 != '') {
                    value: value
                }, function (data) {
        } else {

    $(".username").click(function () {
        var username = $(this).text();
        alert(username); // It doesn't do anything, why?

Oh, I solved it.

It turns out that click event doesn’t work with dynamically generated elements, I had to use on event.

$('#search_result').on('click', '.username', function () {
    alert("it works");
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.