【问题标题】:How to set a value for a selectize.js input?如何为 selectize.js 输入设置值?
【发布时间】:2014-03-24 14:27:20
【问题描述】:

我有一个表单,我想从中复制一些默认值到输入中。表单输入使用 selectize.js 插件。我想以编程方式设置一些表单值。这样做的标准方法:

$("#my_input").val("My Default Value");

不工作。

我尝试过类似的方法,但它也不起作用。

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value"); 

有什么想法吗?一定很简单:)我很想念它。

【问题讨论】:

    标签: javascript jquery html selectize.js


    【解决方案1】:

    检查API Docs

    方法 addOption(data) 和 setValue(value) 可能是您正在寻找的。​​p>


    更新:看到这个答案的受欢迎程度,这里有一些基于 cmets/requests 的附加信息...

    setValue(value, silent)
      将所选项目重置为给定值。
    如果“silent”为真(即:true、1),则不会在原始输入上触发任何更改事件。

    addOption(data)
      添加可用选项或选项数组。如果它已经存在,则不会发生任何事情。
      注意:这不会刷新选项列表下拉菜单(为此使用refreshOptions())。


    响应选项被覆盖:
    这可以通过重新初始化选择而不使用您最初提供的选项来实现。如果您不打算重新创建元素,只需将 selectize 对象存储到变量中:

    // 1. Only set the below variables once (ideally)
    var $select = $('select').selectize(options);  // This initializes the selectize control
    var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')
    
    // 2. Access the selectize object with methods later, for ex:
    selectize.addOption(data);
    selectize.setValue('something', false);
    
    
    // Side note:
    // You can set a variable to the previous options with
    var old_options = selectize.settings;
    // If you intend on calling $('select').selectize(old_options) or something
    

    【讨论】:

    • 我确实阅读了文档并尝试了您的建议。看我的例子。看看不起作用。当我找到答案时,我肯定会踢自己。
    • 您的 jQuery 选择器中的 #my_input 周围没有引号。
    • 感谢您发现错字。我在原始代码中正确设置了它,但在复制到 stackoverflow 时却错过了它。好消息是,正如我所说的那样。我的实际表单中有一个错字,这是导致问题的原因。
    • 您的回答让我走上了正轨。请注意一点:至少在我的测试中,setValue 似乎会默默地关闭不在列表中的选项。有关报告和 jsfiddle,请参见 github.com/brianreavis/selectize.js/issues/568。
    • 当您调用 $("#my_input").selectize() 时,您的原始设置(即插件、渲染函数等)将被覆盖。如何在不覆盖这些设置的情况下让 selectize 对象调用 setValue()?
    【解决方案2】:

    这对我有用:

    var $select = $("#my_input").selectize();
    var selectize = $select[0].selectize;
    selectize.setValue(selectize.search("My Default Value").items[0].id);
    

    但你必须非常确定你只有一场比赛。

    更新:由于此解决方案完美运行,为了使其即使页面上有多个选择元素也能正常工作,我已经更新了答案:

    我们可以按照以下方式进行初始化:

    $('select').each(function (idx) {
        var selectizeInput = $(this).selectize(options);
        $(this).data('selectize', selectizeInput[0].selectize);
    });
    

    在初始化后务实地设置值:

    var selectElement = $('#unique_selector').eq(0);
    var selectize = selectElement.data('selectize');
    if (!!selectize) selectize.setValue("My Default Value");
    

    【讨论】:

    • 感谢您的回答,但对我来说,它无需像这样的搜索 selectize.setValue("My Default Value");你在这个案子上也是对的,我们必须确保价值不会重复。
    【解决方案3】:

    我遇到了同样的问题 - 我在 Rails 中使用 Selectize 并希望选择关联字段 - 我希望关联记录的名称显示在下拉列表中,但我需要每个选项的值记录的 id,因为 Rails 使用 value 来设置关联。

    我通过将@valueAttr 的咖啡脚本变量设置为每个对象的id 并将@dataAttr 的变量设置为记录的name 来解决此问题。然后我浏览了每个选项并设置:

     opts.labelField = @dataAttr
     opts.valueField = @valueAttr
    

    查看完整差异会有所帮助:https://github.com/18F/C2/pull/912/files

    【讨论】:

      【解决方案4】:

      用户“onlyblank”的回答是正确的。对此的一个小补充 - 如果需要,您可以设置多个默认值。

      不是将 id 传递给 setValue(),而是传递一个数组。示例:

      var $select = $("#my_input").selectize();
      var selectize = $select[0].selectize;
      var yourDefaultIds = [1,2]; # find the ids using search as shown by the user onlyblank
      selectize.setValue(defaultValueIds);
      

      【讨论】:

        【解决方案5】:

        注意 setValue 仅适用于已经为选择控件(例如选择字段)预定义的一组值,对于值可以是动态的控件(例如,用户可以在fly, textbox field ) setValue 不起作用。

        使用 createItem 函数代替添加和设置选择字段的当前值

        例如

        $selectize[ 0 ].selectize.clear(); // Clear existing entries
        for ( var i = 0 ; i < data_source.length ; i++ ) // data_source is a dynamic source of data
            $selectize[ 0 ].selectize.createItem( data_source[ i ] , false ); // false means don't trigger dropdown
        

        【讨论】:

          【解决方案6】:

          刚遇到同样的问题,用下面这行代码解决了:

          selectize.addOption({text: "My Default Value", value: "My Default Value"});
          selectize.setValue("My Default Value"); 
          

          【讨论】:

          • 多选怎么办?
          【解决方案7】:

          这是我使用远程搜索标签的完整代码。希望这会有所帮助。

          $('#myInput').selectize({
          valueField: 'id',
          labelField: 'name',
          searchField: 'name',
          options: [],
          delimiter: ',',
          persist: false,
          create: false,
          load: function(query, callback) {
              if (!query.length) return callback();
              $.ajax({
                  url: '/api/all_cities.php',
                  type: 'GET',
                  dataType: 'json',
                  data: {
                      name: query,
                  },
                  error: function() {
                      callback();
                  },
                  success: function(res) {
                      callback(res);
                  }
              });
          },
          onInitialize: function(){
              var selectize = this;
              $.get("/api/selected_cities.php", function( data ) {
                  selectize.addOption(data); // This is will add to option
                  var selected_items = [];
                  $.each(data, function( i, obj) {
                      selected_items.push(obj.id);
                  });
                  selectize.setValue(selected_items); //this will set option values as default
              });
          }
          });
          

          【讨论】:

            【解决方案8】:

            首先加载选择下拉菜单,然后选择它。 它适用于正常的 $(select).val()。

            【讨论】:

              【解决方案9】:

              我遇到了类似的问题。我的数据由远程服务器提供。我想在选择框中输入一些值,但事先不确定该值在服务器上是否有效。

              所以我希望在框中输入值,并且我希望 selectize 以显示可能的选项,就像用户输入了值一样。

              我最终使用了这个 hack(它可能不受支持):

              var $selectize = $("#my_input").selectize(/* settings with load*/);
              var selectize = $select[0].selectize;
              // get the search from the remote server
              selectize.onSearchChange('my value');
              // enter the input in the input field
              $selectize.parent().find('input').val('my value');
              // focus on the input field, to make the options visible
              $selectize.parent().find('input').focus();
              

              【讨论】:

                【解决方案10】:

                一个简化的答案:

                $('#my_input').data('selectize').setValue("Option Value Here");
                

                【讨论】:

                  【解决方案11】:
                  var $select = $(document.getElementById("selectTagName"));
                  var selectize = $select[0].selectize;
                  selectize.setValue(selectize.search("My Default Value").items[0]);
                  

                  【讨论】:

                    猜你喜欢
                    • 2018-09-03
                    • 2021-09-29
                    • 2015-09-23
                    • 2017-11-13
                    • 2022-06-10
                    • 2015-01-13
                    • 1970-01-01
                    • 2017-04-12
                    • 1970-01-01
                    相关资源
                    最近更新 更多