jQuery 组合框/自动完成但可编辑

2024-01-20

我正在使用 jQuery自动完成 http://jqueryui.com/demos/autocomplete/#combobox但我需要它是可编辑的。我的意思是,如果列表中没有某个值,我需要捕获他们输入的值。使用上面链接中的示例,用户可能看不到他们的选择(例如 C#),并且会键入他们的语言。我在默认行为中发现,如果在列表中找不到该值,则会清除用户响应。

我添加了以下代码:

options: {
  allowUserDefined: false
},

and

var self = this,
    **options = this.options,**

and

if (!valid && !options.allowUserDefined) {
  // remove invalid value, as it didn't match anything
  $(this).val("");
  select.val("");
  input.data("autocomplete").term = "";
  return false;
}

以防止响应被清除。这些小小的改变确实有效。但由于列表中未找到 C#,因此没有可返回的选定选项。

如何让代码返回输入字段中输入的内容?在调试代码时,特别是在change事件, input.val() 包含输入的文本,这就是我需要的。我只是不知道如何访问这个值。

谢谢。

这是我完整的js文件:

(function ($) {
    $.widget("ui.combobox", {
        options: {
            allowUserDefined: false
        },
        _create: function () {
            if (this.options.allowUserDefined === null) {
                this.options.allowUserDefined = false;
            }

            var self = this,
                    options = this.options,
                    select = this.element.hide(),
                    selected = select.children(":selected"),
                    value = selected.val() ? selected.text() : "";
            var input = this.input = $("<input>")
                    .insertAfter(select)
                    .val(value)
                    .autocomplete({
                        delay: 0,
                        minLength: 0,
                        source: function (request, response) {
                            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                            response(select.children("option").map(function () {
                                var text = $(this).text();
                                if (this.value && (!request.term || matcher.test(text)))
                                    return {
                                        label: text.replace(
                                            new RegExp(
                                                "(?![^&;]+;)(?!<[^<>]*)(" +
                                                $.ui.autocomplete.escapeRegex(request.term) +
                                                ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                            ), "<strong>$1</strong>"),
                                        value: text,
                                        option: this
                                    };
                            }));
                        },
                        select: function (event, ui) {
                            ui.item.option.selected = true;
                            self._trigger("selected", event, {
                                item: ui.item.option
                            });
                        },
                        change: function (event, ui) {
                            if (!ui.item) {
                                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                    valid = false;
                                select.children("option").each(function () {
                                    if ($(this).text().match(matcher)) {
                                        this.selected = valid = true;
                                        return false;
                                    }
                                });
                                if (!valid && !options.allowUserDefined) {
                                    // remove invalid value, as it didn't match anything
                                    $(this).val("");
                                    select.val("");
                                    input.data("autocomplete").term = "";
                                    return false;
                                }
                            }
                        }
                    })
                    .addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append("<a>" + item.label + "</a>")
                        .appendTo(ul);
            };

            this.button = $("<button type='button'>&nbsp;</button>")
                    .attr("tabIndex", -1)
                    .attr("title", "Show All Items")
                    .insertAfter(input)
                    .button({
                        icons: {
                            primary: "ui-icon-triangle-1-s"
                        },
                        text: false
                    })
                    .removeClass("ui-corner-all")
                    .addClass("ui-corner-right ui-button-icon")
                    .click(function () {
                        // close if already visible
                        if (input.autocomplete("widget").is(":visible")) {
                            input.autocomplete("close");
                            return;
                        }

                        // work around a bug (likely same cause as #5265)
                        $(this).blur();

                        // pass empty string as value to search for, displaying all results
                        input.autocomplete("search", "");
                        input.focus();
                    });
        },

        destroy: function () {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);

Update

使用 Darkajax 的代码(我比我想出的更喜欢严格选项),我可以通过这样做来获取输入框的值:

var valu = $("#combobox").parent().children()[1].value;

当使用 jQuery UI 自动完成组合框时,我自己所做的就是声明组合框小部件,如下所示:

(function( $ ) {
    $.widget( "ui.combobox", {
        // default options
        options: {
            strict: false
        },
        _create: function() {
            var self = this,
                select = this.element.hide(),
                selected = select.children( ":selected" ),
                value = selected.val() ? selected.text() : "",
                strict = this.options.strict;

            var input = this.input = $( "<input>" )
                .insertAfter( select )
                .val( value )
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: function( request, response ) {
                        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                        response( select.children( "option" ).map(function() {
                            var text = $( this ).text();
                            if ( this.value && ( !request.term || matcher.test(text) ) )
                                return {
                                    label: text.replace(
                                        new RegExp(
                                            "(?![^&;]+;)(?!<[^<>]*)(" +
                                            $.ui.autocomplete.escapeRegex(request.term) +
                                            ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                        ), "<strong>$1</strong>" ),
                                    value: text,
                                    option: this
                                };
                        }) );
                    },
                    select: function( event, ui ) {
                        ui.item.option.selected = true;
                        self._trigger( "selected", event, {
                            item: ui.item.option
                        });
                    },
                    autocomplete : function(value) {
                        this.element.val(value);
                        this.input.val(value);
                    },
                    change: function( event, ui ) {
                        if ( !ui.item ) {
                            var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                                valid = false;
                            select.children( "option" ).each(function() {
                                if ( this.value.match( matcher ) ) {
                                    this.selected = valid = true;
                                    return false;
                                }
                            });
                            if ( !valid ) {
                                // if strict is true, then unmatched values are not allowed
                                if ( strict ) {
                                    // remove invalid value, as it didn't match anything
                                    $( this ).val( "" );
                                    select.val( "" );
                                }
                                return false;
                            }
                        }
                    }
                })
                .addClass( "ui-widget ui-widget-content ui-corner-left" );

            input.data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item.label + "</a>" )
                    .appendTo( ul );
            };

            this.button = $( "<button type=\"button\" class=combo_button>&nbsp;</button>" )
                .attr( "tabIndex", -1 )
                .attr( "title", "Show All Items" )
                .insertAfter( input )
                .button({
                    icons: {
                        primary: "ui-icon-triangle-1-s"
                    },
                    text: false
                })
                .removeClass( "ui-corner-all" )
                .addClass( "ui-corner-right ui-button-icon" )
                .click(function() {
                    // close if already visible
                    if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                        input.autocomplete( "close" );
                        return;
                    }

                    // pass empty string as value to search for, displaying all results
                    input.autocomplete( "search", "" );
                    input.focus();
                });
        }
    });
})( jQuery );

这将使它接受其他选项作为有效值,您只需使用:

$("#combobox").combobox({
    strict: true
});

让它作为默认值工作,以防万一您需要它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jQuery 组合框/自动完成但可编辑 的相关文章

随机推荐

  • Android:通过视频动态模糊表面

    我正在构建一个 Android 应用程序 其中 ExoPlayer 在 SurfaceView 的表面上播放视频 并且我正在研究是否可以动态模糊播放的视频 涉及首先生成要模糊的视图位图的模糊技术将不起作用 因为 SurfaceView 的表
  • WIX 安装程序未正确显示 WixUI 对话框的自定义图像

    In my WIX我正在使用自定义安装程序WixUIDialogBmp安装人员的图像Welcome and Completion页 但如下图所示 图像无法正确显示 我正在尝试遵循这个官方文档 http wixtoolset org docu
  • 解决这个分配珠子难题的算法?

    假设你有一个圆圈 如下所示 N点 并且你有N珠子分布在槽中 Here s an example 每个珠子都可以顺时针移动X插槽 这需要花费X 2美元 您的目标是最终在每个槽中获得一颗珠子 完成这项任务至少需要花多少钱 这个问题更有趣的变体
  • 加载后获取 Highcharts 系列数据

    我试图在调用 Highcharts 图表并将其加载到页面后获取系列数据 到目前为止 我只成功地获得了一堆字符串 这显然不是我想要的 不知道是否有人可以帮助我解决这个问题 jQuery 代码 success function chartDat
  • Spring AOP 创建额外的 bean

    我正在玩Spring AOP 这是一个简单的类 public class CModel extends Car private double torqueMeasure 1 public CModel System out println
  • 如何使用 kubernetes python 客户端排空节点?

    我正在尝试使用官方的 kubernetes 工作节点自动化kubernetes python 客户端 https github com kubernetes incubator client python 我目前正在寻找一种方法安全地将所有
  • Jena Fuseki 服务器命令未找到

    我是 Jena Fuseki 服务器的新手 根据链接http jena apache org documentation serving data index html http jena apache org documentation
  • 如何在 jenkins 上使用 ant 从 .product 构建 eclipse rcp 应用程序

    我想构建一个 Eclipse RCP 应用程序 我有一个产品配置文件和一个带有许多第三方插件的目标平台 从 Eclipse IDE 的导出工作完美无缺 但这很难说是专业的 所以我也想让它在詹金斯上工作 构建服务器从 SVN 获取文件 没有
  • matlab/octave - 广义矩阵乘法

    我想做一个函数来概括矩阵乘法 基本上 它应该能够执行标准矩阵乘法 但它应该允许通过任何其他函数更改两个二元运算符的乘积 和 目标是在 CPU 和内存方面尽可能高效 当然 它的效率总是低于 A B 但操作员的灵活性是这里的重点 这是我阅读后可
  • `this.some_property` 在匿名回调函数中变为未定义

    所以我不太明白为什么这个变量这个任务在我的目标对象内部的添加事件侦听器中变得未定义 我有一种感觉 它可能与异步编程有关 我仍然不完全理解 抱歉 我有点 JS 菜鸟 但是如果你们能向我解释我做错了什么以及什么可能是更好的解决方案 那就太棒了
  • 使用 Azure AD 多租户进行 Azure AD B2C 身份验证

    我已按照本文配置了 Azure AD 多租户身份验证 https learn microsoft com en us azure active directory b2c identity provider azure ad multi t
  • 如何刷新 iframe url?

    我正在使用 ionic 创建一个应用程序 其中使用 iframe 显示 URL 这是 HTML 代码 这是角度js scope iframeHeight window innerHeight document getElementById
  • 自适应卡 - 以字节为单位提供图像

    我正在尝试将图像放入 Bot 框架中的自适应卡中 如下所示 card Body Add new AdaptiveImage Type Image Url new Uri pictureUrl Size AdaptiveImageSize L
  • jQuery .val() 在更改选择框时返回未定义

    我有一个带有一些日期的选择框 我想在输入更改时获取所述日期的值 我的价值总是变得不确定 date pick change function var values date pick selected val alert values Fid
  • 在 C# 中直接在 DateTimePicker 上转到月份和年份

    如果用户在我的中输入日期 我该如何实现这一点DateTimePicker它会自动聚焦月份部分 输入该月份部分后 会转到年份部分 因为我不希望他必须按右键才能聚焦 有没有办法以编程方式执行此操作 用户不可能已经单击月份或年份部分 因为他使用键
  • 构建管道的默认分支。这是什么意思?

    在 Azure DevOps Services 的发布工作流程中 在设置持续部署触发器时 有一个选项 构建管道的默认分支 我不明白这意味着什么以及如何查看项目中不同管道的默认分支 任何有关这方面的文档的参考也会有所帮助 这也出现在管道中的其
  • 如何将 DataFrame 的列名从字符串转换为整数

    在下面的代码中 我将一个字符串读入 DataFrame 但即使输入字符串的标头是数字 它们也会作为字符串读入 1 2 有没有办法将它们作为数字读取 或者随后将它们转换为数字 import pandas as pd from StringIO
  • java初学者:如何在哈希图中对键进行排序?

    我是java新手 正在学习哈希图的概念 我很困惑哈希图中的键是如何排序的 我知道它基于字符串长度 但我很困惑当字符串长度相同时数据如何排序 import java util HashMap import java util Iterator
  • 如何向后读取文件以有效地查找子字符串

    我有一个巨大的这种结构的日志文件 时间戳 标识符 值 1463403600 AA 74 42 1463403601 AA 29 55 1463403603 AA 24 78 1463403604 AA 8 46 1463403605 AA
  • jQuery 组合框/自动完成但可编辑

    我正在使用 jQuery自动完成 http jqueryui com demos autocomplete combobox但我需要它是可编辑的 我的意思是 如果列表中没有某个值 我需要捕获他们输入的值 使用上面链接中的示例 用户可能看不到