我正在其中一个搜索输入上创建一个自动完成功能,并且除其中最后一个部分外,其余大部分功能都可以正常工作,如果没有单击标签,最后一个部分将使系统识别输入是否与标签匹配。
例如,如果在输入框中键入“伦敦”,但用户未单击“伦敦”的标签,则不会发送标签的值,也不会获得与伦敦相同的结果值以空值发送。
所以我要实现的是,如果在输入框中键入london但未单击标签,则单击提交按钮时,将发送与london匹配的标签。仅当直接匹配“ london”时才必须直接匹配。我该怎么做?
到目前为止,这是我的代码:
html:
<div class="search-homepage-input">
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9 col-l">
{!! Form::text('sl', null, array('class' => 'form-control shop-input', 'maxlength' =>'50', 'placeholder' => 'Search by city. Eg. London, New York, Paris...', 'id' => 'sl')) !!}
</div>
{!! Form::hidden('country', null, array('id' => 'country')) !!}
{!! Form::hidden('city', null, array('id' => 'city')) !!}
<div class="col-md-3 col-r">
{!! Form::submit('Find Shops', array('class' => 'btn btn-homepage-search')) !!}
</div>
{!! Form::close() !!}
</div>
PHP laravel:
public function autoComplete(Request $request){
$query = $request->term;
$res = City::where('name', 'LIKE', "%$query%")->orderBy('name')->paginate(5);
foreach($res as $cities ){
$usersArray[] = array(
"label" => $cities->name,
"value" => $cities->id,
"country" => $cities->countries->id,
"countryname" => $cities->countries->country
);
}
return response()->json($usersArray);
}
JS:
$('#sl').autocomplete({
source: countries,
select: function(event, ui) {
event.preventDefault();
if (ui.item.label === "No results found") {
$("#sl").val("");
return false;
}
$("#country").val(ui.item.country); // save selected id to hidden input
$("#city").val(ui.item.value); // save selected id to hidden input
$('#sl').val(ui.item.label + ', ' + ui.item.countryname)
},
focus: function(event, ui) {
event.preventDefault();
$('#sl').val(ui.item.label);
},
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: 'No results found'
};
ui.content.push(noResult);
}
}
});
$("#sl").autocomplete("widget").menu("option", "items", "> li:not('.no-select')");
$("#sl").autocomplete("instance")._renderItem = function(ul, item) {
var li = $("<li>");
if (item.country == undefined) {
li.addClass("no-select").append(item.label);
} else {
li.append("<div><strong>" + item.label + "</strong>, " + item.countryname + "</div>");
}
return li.appendTo(ul);
}