【问题标题】:Add checkbox to auto complete -jQuery添加复选框以自动完成-jQuery
【发布时间】:2015-06-19 05:21:08
【问题描述】:

我正在处理这段代码,并且我使用 jQuery UI 进行自动完成。现在我需要一些帮助来添加复选框,以便我可以进行多项选择,并以逗号分隔反映我的字段。我找到了一个正是我想要创建的插件,但我不想为 [我的工作] 使用任何插件 http://www.igniteui.com/combo/selection-and-checkboxes

<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<link rel="stylesheet" href="js/jquery-ui.css">
<body>
    <input id="condition" type="text" placeholder="condition">
</body>
<script>
    var availableTags = [
               "ActionScript",
               "AppleScript",
               "Asp",
               "BASIC",
               "C",
               "C++",
               "Clojure",
               "COBOL",
               "ColdFusion",
               "Erlang",
               "Fortran",
               "Groovy",
               "Haskell",
               "Java",
               "JavaScript",
               "Lisp",
               "Perl",
               "PHP",
               "Python",
               "Ruby",
               "Scala",
               "Scheme"
    ];

    $(document).ready(function () {
        $('#condition').autocomplete({
            source: availableTags,
            minLength: 0
        }).focus(function () {
            try {
                $(this).autocomplete("search");
            }
            catch (e) {

            }
        });
    });
</script>

【问题讨论】:

  • 我不想在工作中使用任何插件,那为什么要使用 jquery?
  • 任何由第三方创建的插件都会产生依赖关系,它也会与 jquery ui 相矛盾。我不希望它使任何未来的工作或扩展受到任何插件的影响
  • 您正在发布重复的内容:stackoverflow.com/questions/30913983/…
  • 因为我有某种紧急情况,甚至没有回复。

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


【解决方案1】:

基本上你首先需要改变 jQuery 自动完成的输出。

类似的东西

$('yourElement').autocomplete({ /* autocomplete config here */ }).data( "autocomplete" )._renderItem = function( ul, item ) {
    var checked = ($.inArray(item.label, selectedItems) >= 0 ? 'checked' : '');

    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( '<a><input type="checkbox" ' + checked + '/>' + item.label + '</a>' )
        .appendTo( ul );
};

然后你必须将选取的元素存储在一个变量(一个数组)中

$('#yourElement').autocomplete({
    // Configs
    select:function(event, ui) {// Onselect event
        // Don't forget to check if the item is already in the array
        // and if it's the case to remove it

        selectedItems.push(ui.item.label); 
    }
});

不要认为 selectItems 是一个数组,您需要在脚本中定义

您可以在 JSFiddle 上看到此代码将在自动完成列表中输出什么

希望对你有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2021-11-16
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多