繁体   English   中英

在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> 

我们基本上禁止搜索,直到我们在该字段中看到@ 那时,我们将用户编写的内容与您的主机名配对。

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM