Jquery .click() not working with livesearch

101 views Asked by At

I've implemented a live search basing on the string written in an input form. Results are displayed correctly in this way:

<input type="text" class="form-control" name="search_client" id="search_client" required autocomplete="off">
<ul id="results_client" class="liveresults">
    <li class="liveresult">
        <h5 class="result_name" data-value="Joo Fogn"><i class="fa fa-user fa-fw"></i> Joo Fogn</h5>
    </li>
    <li class="liveresult">
        <h5 class="result_name" data-value="Peter Nash"><i class="fa fa-user fa-fw"></i> Peter Nash</h5>
    </li>
</ul>

However I'd like to autocomplete the input with the showed result when a user click on one of the possible results.

To do it, I though to intercept the click on the result and give the result value to the input, as follows:

$(".result_name").click(function(){     
    $("#search_client").val($(".result_name").data("value"));
});

However when I click on a result, nothing happens. How can I fix it?

2

There are 2 answers

1
Bhushan Kawadkar On BEST ANSWER

Try this : You can use .on() to bind click event and use $(this) to get clicked element jQuery instance to read its data value.

$(document).on("click",".result_name",function(){     
    //use $(this) to get clicked element and read its value
    $("#search_client").val($(this).data("value"));
});
0
Keval Bhatt On

see this example: http://jsfiddle.net/kevalbhatt18/g393kqgd/1/

$(".result_name").click(function(){   
    $("#search_client").val($(this).data("value"));
});