自动完成未返回任何结果

时间:2018-11-21 12:53:57

标签: javascript jquery jquery-ui autocomplete

当数据不匹配时,如何在自动完成中返回无结果标签,目前它什么也没显示。

这是我当前的代码: HTML:

{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
            <div class="col-md-9">
            {!! Form::text('searchlocation', null, array('class' => 'form-control', 'maxlength' =>'55', 'placeholder' => 'Eg. England, London or Sports', 'id' => 'sl')) !!}
            </div>
            {!! Form::hidden('country', null, array('id' => 'country')) !!}
            {!! Form::hidden('city', null, array('id' => 'city')) !!}
            <div class="col-md-3">
                {!! Form::submit('Find Sights', array('class' => 'btn btn-homepage-search'))  !!}
            </div>
            {!! Form::close() !!}

JS:

$('#sl').autocomplete({
    source: '/autocomplete',
    select: function(event, ui) {
        event.preventDefault();
        $("#country").val(ui.item.country); 
        $("#city").val(ui.item.value); 
        $('#sl').val(ui.item.label);
    },
    focus: function(event, ui){
        event.preventDefault();
        $('#sl').val(ui.item.label);
    },

})

2 个答案:

答案 0 :(得分:0)

您可以在php中将其设置为:

if(count($usersArray) < 1){
        $usersArray[] = array(
            "label" => "No Result",
            "value" => "-1",
            "country" => "-1"
        );
    }

答案 1 :(得分:0)

您可以使用客户端检查显示未找到任何记录。请在下面看看。

$(function() {
    $("#SearchUser").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "http://api.stackexchange.com/2.1/users",
                data: {
                    site: 'stackoverflow',
                    inname: request.term
                },
                dataType: 'jsonp'
            }).done(function(data) {
                if (data.items) {
                    response($.map(data.items, function(item) {
                        console.log(item);
                        return item.display_name + " " + item.location;
                    }));
                }
            });
        },
        minLength: 1,
        response: function(event, ui) {
            if (!ui.content.length) {
                var message = { value:"",label:"No records found" };
                ui.content.push(message);
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet"/>
<label for="SearchUser">StackOverflow user:</label>
<input id="SearchUser" type="text" />