Last active
May 8, 2017 06:55
-
-
Save RakibSiddiquee/9e68635b6124fb44a539c92557abd859 to your computer and use it in GitHub Desktop.
Autocomplete an input field from database using jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html lang="en-US"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Jquery sortable serialize</title> | |
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> | |
<style> | |
.ui-widget.ui-widget-content{max-height: 500px; overflow-y: scroll; overflow-x: hidden;} | |
.item{list-style: none; background: lightgray; padding: 5px; margin: 2px 0; width: 500px; cursor: move;} | |
</style> | |
</head> | |
<body> | |
<form action="" method="post" class="form-inline"> | |
<div class="form-group"> | |
<label for="newsHeading" class="control-label">News Heading </label> | |
<input type="text" name="term" id="newsHeading" class="form-control" placeholder="News ID / Title..."> | |
<input type="hidden" name="newsId" id="newsId"> | |
</div> | |
</form> | |
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> | |
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> | |
<script> | |
$(function() { | |
$("#newsHeading").autocomplete({ // For news title autocomplete | |
source: "{{ url('news-position/keyword') }}", // pass the source url or a php script file in which we will catch the term keyword to search data | |
/* If we want to pass more parameters in the url, write the following like following... | |
source: function(request, response) { | |
$.get("{{ url('backend/news-position/keyword') }}", { posId: $('#positionId').val(), term: $('#newsHeading').val() }, response); | |
} | |
*/ | |
minLength: 1, | |
select: function(event, ui) { | |
console.log(ui.item); | |
$('#newsId').val(ui.item.id); | |
} | |
}); | |
}); | |
</script> | |
<!-- // PHP part | |
$term = $request->term.'%'; // catch the keyword using $_GET['term'] or request | |
$data = BnContent::select('content_id', 'content_heading', 'created_at') // Get data from the database using like keyword | |
->where('content_id', 'like', $term) | |
->orWhere('content_heading', 'like', $term) | |
->where('deletable', 1)->get(); | |
$return_array = []; // take an empty array | |
foreach ($data as $v) { // loop the data and pass it using value and id key of array | |
$return_array[] = array('value' => $v->content_id . ' - ' . $v->content_heading . ' (' . $v->created_at .')' , 'id' =>$v->content_id); | |
} | |
return response()->json($return_array); // At last pass the data to frontend using json encoded | |
--> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment