在 jquery-ui 自动完成上设置自定义输入字段值

Setting a custom input field value on jquery-ui autocomplete

我正在尝试使用 jquery-ui 的自动完成功能将电子邮件域的后缀(例如 @gmail.com@yahoo.com)添加到现有值聚焦时的文本字段。

以下是我的代码:

$('body').on('focusin', '#id_email', function () {
    console.log("Focused")
    $('#id_email').autocomplete({
        minLength: 0,
        autoFocus: true,
        source: ["@gmail.com", "@yahoo.com", "@yahoo.co.in", "@hotmail.com", "@live.com"],
        select: function (event, ui) {
            var suffix = ui.item.value;
            existing_val = $("#id_email").val();
            new_val = existing_val + suffix;
            console.log(`Existing value"${existing_val} Suffix: ${suffix} New value:${new_val}`);
            $("#id_email").val(new_val);
        }
    }).focus(function () {
        $(this).autocomplete("search", "");
    })
});

问题是,即使我有在选择自动完成选项之一时为文本字段设置新值的代码,所选值也会替换该字段的现有值。控制台输出:

Existing value"joelg@ Suffix: @gmail.com New value:joelg@@gmail.com

根据输出,文本字段的新值应为 joelg@@gmail.com。然而实际发生的是,即使文本字段最初包含 joelg@ 的初始值,在聚焦该字段时,会显示自动完成菜单,并且在选择“@gmail.com”时,现有值是替换为“@gmail.com”,而不是输入字段获得值 joelg@@gmail.com.

这似乎与您尝试的有点不同。基本上,您希望在 @ 出现在字段中之前避免搜索,然后根据您的列表在那时构建多个电子邮件地址。

看看这个例子。

$(function() {
  // Common Hosts Array
  var hosts = ["gmail.com", "yahoo.com", "yahoo.co.in", "hotmail.com", "live.com"];
  $("#email").autocomplete({
    minLength: 0,
    source: function(req, resp) {
      // Result Array
      var results = [];
      // Email Prefix (before @)
      var pre = req.term.slice(0, req.term.indexOf("@"));
      // Iterate each host, building a number of email addresses
      $.each(hosts, function(key, host) {
        results.push(pre + "@" + host);
      });
      resp(results);
    },
    search: function(e, ui) {
      // Check for instancwe of @ symbal and cancel search until found
      if ($(this).val().indexOf("@") <= 0) {
        return false;
      }
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="ui-widget">
  <label for="email">Email: </label>
  <input id="email">
</div>

我们基本上会抑制搜索,直到我们在字段中看到 @。届时,我们会将用户写入的内容与您的主机名配对。