【问题标题】:Add values to a chosen multiselect将值添加到选定的多选
【发布时间】:2013-08-13 05:22:21
【问题描述】:

我想知道是否可以即时向chosen.js 多选添加新值(类似于标记的工作方式)。

我在另一个SO post 中看到一位用户说这是可能的。他在 github 上链接到 examplefork,但我在实现这些时遇到了一些困难。

源代码是用 CoffeeScript 编写的。我尝试将它(使用在线编译器)编译为常规 JavaScript,将代码复制粘贴到空白测试项目中,但出现错误。之后,我也加载了 AbstractChosen 和 SelectParser(将它们编译为 js)并且没有出现错误,但是“动态添加项目”功能不存在(尽管我初始化了 @987654325 中描述的选择@)。

有人用过这个叉子吗?如果是,您能分享一下您的经验吗?

【问题讨论】:

    标签: javascript jquery-chosen


    【解决方案1】:

    您遇到的问题是因为您没有按照the documentation中的步骤操作:

    如果您下载源代码,请安装正确的软件包并运行以chosen.jquery.jschosen.proto.jschosen.css 结尾的构建命令。

    所以以下步骤应该为您完成:

    1. 下载:https://github.com/koenpunt/chosen/archive/option_adding.zip
    2. 安装包:npm install && gem install bundler && bundle install
    3. 运行构建:grunt build(注意,为此您需要 grunt cli

    编辑

    或者为了您的方便,download a compiled release

    【讨论】:

    • 感谢您对 grunt 的澄清(关于第 3 步的注释)。我尝试过使用 npm install -g grunt,但是 CLI 没有提供(现在我看到 grunt-cli 是正确的方法)。另外,感谢 zip,在我看来,这种方式更容易,因为(我相信)coffeescript 层为没有使用它的用户或更习惯于 vanilla javascript 的用户增加了复杂性。非常感谢!
    • @Koen。我假设您是该分叉的作者,我向您发送了一个拉取请求 github.com/koenpunt/chosen/pull/49 以更新 readme.md 罚款,因为您的 jumpshare 链接已过期。
    【解决方案2】:

    文档中提到了这个选项:

    动态更新选择

    如果您需要更新选择字段中的选项并希望选择 要获取更改,您需要触发“选择:更新” 场上的事件。 Chosen 将根据更新的内容重新构建自己 内容。

    有了这个。

    $("#form_field").trigger("chosen:updated");
    

    这可以结合

    // Add field
    $("#form_field").append("<option>Utopia</option>");
    
    $("#form_field").trigger("chosen:updated");
    

    可以在 jsfiddle 中找到将其添加到示例中: http://jsfiddle.net/E5X9x/

    【讨论】:

    • 啊,我明白了。我期待与此类似的功能:xoxco.com/projects/code/tagsinput。这是不可能通过选择来实现的吗?我的意思是,我知道我可以以某种方式获取所选输入的 val(),进行检查,并最终在用户点击选项卡或输入后将其作为选项附加,但我正在尝试查看这种可能性是否内置(在我提到的叉子中)。非常感谢您的意见!
    • @Zubzob 所说的 fork(我的 fork)能够使用 Chosen 的界面添加选项。您可以在此处找到此功能的文档:github.com/harvesthq/chosen/pull/166
    【解决方案3】:

    解决办法是here

    $('select').chosen({plugins: ['option-adding']});
    

    $(function() {
      $(".chzn-select").chosen({
        create_option: true,
        // persistent_create_option decides if you can add any term, even if part
        // of the term is also found, or only unique, not overlapping terms
        persistent_create_option: true,
        // with the skip_no_results option you can disable the 'No results match..' 
        // message, which is somewhat redundant when option adding is enabled
        skip_no_results: true
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多