清除输入文本时如何隐藏 ajax 搜索结果


I could finally get my ajax search work, but I couldn't hide the results when I clear the input text box. Also, I couldn't select the search result so that it should retain in the input text box

这是 Ajax 代码:阿贾克斯.js

$(function () {
$('#search').keyup(function () {
    $.ajax({
        type: "POST",
        url: "search",
        data: {
            'search_text': $('#search').val(),
            'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
        },
        success: searchSuccess,
        dataType: 'html'
    });
});
});
function searchSuccess(data, textStatus, jqXHR) {
$('#search-results').html(data);
}

这是 html 模板模板.html

<input type="text" id="search" name="search" class="search" value="Enter Loc" size="35" maxlength="300" style="margin-left:10px;color:#d5caca" onclick="document.getElementById('search').value = ''" />
    <a class="lr" style="text-decoration:none" href="#">Search</a>
    <ul id="search-results" style="color:#ffffff;margin-left:35%">
    </ul>

提前感谢您的帮助!

如果值为空,则清除结果面板

$(function () {
    $('#search').keyup(function () {
        //clear result panel if the value is blank
        if (!this.value.trim()) {
            $('#search-results').html('');
            return;
        }
        $.ajax({
            type: "POST",
            url: "search",
            data: {
                'search_text': $('#search').val(),
                'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });
    });
});
function searchSuccess(data, textStatus, jqXHR) {
    $('#search-results').html(data);
}

最新更新