Can I get only id of the value in autocomplete search in Laravel? The current situation is like I am getting the value of employer name, but I want to get the id of employer name, so I can save it to another table in the database without saving of the employer name.
Here is my controller code:
public function index2(){
return view('autocomplete.index');
}
public function autoComplete2(Request $request) {
$query = $request->get('term','');
$products=Employer::where('employer_name','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($products as $product) {
$data[]=array('value'=>$product->employer_name,'id'=>$product->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
Here is my view:
{!! Form::open(['route' => 'calllogs.store', 'method' => 'post']) !!}
<div class="form-group">
{!! Form::label('Company Recommend ') !!}
<input class="typeahead form-control" value="" type="text" name="searchajax" id="search_text">
</div>
{!! Form::submit(__('Create'), ['class' => 'btn btn-primary pull-right']) !!}
{!! Form::close() !!}
<script>
$(document).ready(function() {
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 1,
});
});
</script>
Any helps would be appreciated.
This is not related to laravel but for Jquery UI.jqueryUI autocomplete has a option call 'select' and it trigger after clicked on a autocomplete list item.
$(document).ready(function() {
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
select: function (event, ui) {//trigger when you click on the autocomplete item
event.preventDefault();//you can prevent the default event
alert( ui.item.id);//employee id
alert( ui.item.value);//employee name
},
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 1,
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.