我正在尝试使用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
值的输入字段。
发布于 2019-09-05 23:24:28
这看起来可能与您尝试的略有不同。基本上,您希望在字段中出现@
之前避免搜索,然后根据您的列表构建多个电子邮件地址。
看一下这个例子。
$(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>
我们基本上禁止搜索,直到我们在现场看到@
。此时,我们将获取用户编写的内容,并将其与您的主机名配对。
希望这能有所帮助。
https://stackoverflow.com/questions/57805095
复制