输入时不要显示jQuery UI Autocomplete

时间:2015-02-17 23:45:24

标签: javascript jquery jquery-ui jquery-ui-autocomplete

我正在使用jQuery UI自动完成功能来显示文本输入的自动完成功能。我希望列表出现时更加保真。我已经为Click和Double Click制作了触发器,显示自动完成(基于用户是否选择包含每个触发器)但我发现无法影响键入时是否显示自动完成。

如何在键入时不显示自动完成(不是由键事件触发)?

答案

function InitialiseAutoCompleteEx(inputId, trigOnClick, trigOnDoubleClick, trigOnType, trigOnCtrlSpace, rawAutoCompleteItems)
{
    var autoCompleteItems = rawAutoCompleteItems.split("|");
    var input = $("#" + inputId);

    input.autocomplete(
        {
            source: autoCompleteItems,
            minLength: 0,
            disabled: true,
            close: function() { $(this).autocomplete("option", "disabled", true); }
        });

    if (trigOnClick)
    {
        input.click(function()
            {
                $(this).autocomplete("option", "disabled", false);
                $(this).autocomplete("search");
            });
    }

    if (trigOnDoubleClick)
    {
        input.dblclick(function()
            {
                $(this).autocomplete("option", "disabled", false);
                $(this).autocomplete("search");
            });
    }

    if (trigOnType)
    {
        input.keydown(function(event)
            {
                var key = String.fromCharCode(event.which);

                if ( /[a-zA-Z0-9]/.test(key) )
                {
                    $(this).autocomplete("option", "disabled", false);
                    $(this).autocomplete("search");
                }
            });
    }

    if (trigOnCtrlSpace)
    {
        input.keydown(function(event)
            {
                if (event.which == 32 && event.ctrlKey)
                {
                    $(this).autocomplete("option", "disabled", false);
                    $(this).autocomplete("search");
                    event.preventDefault();
                }
            });
    }
}

1 个答案:

答案 0 :(得分:3)

只需使用其disabled option

$("#field").autocomplete("option", "disabled", true);

var tags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"];
$("#field").autocomplete({
  source: function(request, response) {
    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
    response($.grep(tags, function(item) {
      return matcher.test(item);
    }));
  },
  disabled: true,
});

function disable(shouldDisable) {
  shouldDisable = JSON.parse(shouldDisable); // Extract boolean from string parameter
  $("#field").autocomplete("option", "disabled", shouldDisable);
  $("#field").focus().trigger($.Event("keydown"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<input id="field" />
<button onclick="disable(false);">Autocomplete On</button>
<button onclick="disable(true);">Autocomplete Off</button>