nameless nameless - 24 days ago 11
Javascript Question

Laravel Live Search AJAX Eloquent Clickable Items

I followed this tutorial to create a live search with AJAX and Eloquent (accessing the DB) in a laravel app. Now I'm wondering, how I can make the search results clickable, so the thing I click is entered in the input field. Somehow, just adding a click handler and then setting

.val()
to the query seems to not be working (expect I made a mistake)... PS: I'm using jQuery as well.

How could I do that? Here the code, to be precise:

blade template:

<div id="content">
<input type="search" name="keyword" placeholder="Search Names" id="searchbox">
<div id="results"></div>
</div>


JS in there (don't wonder, I added a little thing to wait for the user to finish typing before sending AJAX request):

$(document).ready(function () {
var typingTimer; //timer identifier
var doneTypingInterval = 300; //time in ms (5 seconds)

$("#searchbox").on('keyup', function () {
clearTimeout(typingTimer);
if ($('#searchbox').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
});

//user is "finished typing," do something
function doneTyping() {
var key = $('#searchbox').val();

if (key.length >= 3) {
$.ajax({
url: '/categorysearch/' + key,
type: 'GET',
beforeSend: function () {
$("#results").slideUp('fast');
},
success: function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});

}
}


and php file/function processing:

public function Index(Request $request){
$query = "%".$request->categorySearchTerm."%";
$categories = Subcategory::where('name','LIKE',$query)->get();
foreach($categories as $category){
echo "<div id='item'>$category->name</div>";
}
}


Now how can I get what I want, so clicking on the item puts the content of the item in the input field?

Answer

You can try adding the category as data attribute to get after with jQuery something like this:

public function Index(Request $request){
    $query = "%".$request->categorySearchTerm."%";
    $categories = Subcategory::where('name','LIKE',$query)->get();
    foreach($categories as $category){
        echo "<div id='item' data-name='$category->name'>$category->name</div>";
    }
}

then you can get the value and set with a function like this:

$(document).on('click', '#item', function() {
    $('input').val($(this).data('name'));
});

Here the idea working: https://jsfiddle.net/yhwsy6x7/1/

Comments