我可以在Laravel中只获取自动完成搜索中的值的ID吗?目前的情况就像我得到了雇主名称的价值,但我想得到雇主姓名的id,所以我可以将它保存到数据库中的另一个表而不保存雇主名称。
这是我的控制器代码:
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'=>''];
}
以下是我的观点:
{!! 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>
任何帮助都将不胜感激。
答案 0 :(得分:0)
这与laravel无关,但对于Jquery UI.jqueryUI自动完成有一个选项调用&#39; select&#39;并在点击自动填充列表项后触发。
$(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,
});
});