【问题标题】:Limit the jQuery select2 maximum selected options限制 jQuery select2 最大选择选项
【发布时间】:2013-11-05 13:21:40
【问题描述】:

我参考了 select2 jQuery 插件提供的这个文档。 http://ivaynberg.github.io/select2/

但是当我使用此代码来限制用户一次可以选择的选项数量时:

$(document).ready(function(){
    $(".select2").select2({ maximumSelectionSize: 2 });
    });

这里是select标签的html:

  <select id="store-name" name="state[]" class="select2-select-00 span6" multiple size="5"
            data-placeholder="Store" style="height:25px;">


        <?php foreach ($this->Store->get_all_stores_names() as $row) {

        //print_r($row);
          echo '<option value="' . $row->name . '"> ' . $row->name . '</option>';
        }
        ?>

    </select>

当我尝试限制它时,我在控制台中收到此错误:

Uncaught TypeError: Object [object Object] has no method 'select2'

为什么?我的意思是select2工作正常,这意味着它的js文件正在加载,那为什么我无法限制呢?

【问题讨论】:

  • 我在你的 html 中没有看到 .select2
  • 我什至用这样的 id 选择器尝试过:jQuery("#store-name").select2({ maximumSelectionSize: 2 });还是一样的错误。

标签: javascript limit jquery-select2 uncaught-exception


【解决方案1】:

像这样使用 ma​​ximumSelectionLength

$("#selectQQQ").select2({
    maximumSelectionLength: 3
});

扩展

Select2 有data-* attributes

意思是,您可以将 maximumSelectionLength 参数设置为 HTML5 数据属性,如下所示:

<select data-placeholder="Select a state" data-maximum-selection-length="2" ...>

【讨论】:

  • 是否可以添加 data-maximumSelectionLength="2" ?
  • @AbhiBurk,它不起作用吗?你的错误信息是什么?\
  • 没有错误,它在元素 data-maximum-selection-length="2" 上使用它
  • 你是对的,我忘记在答案中设置数据属性方式。谢谢。
猜你喜欢
  • 2019-04-19
  • 1970-01-01
  • 2015-07-26
  • 2018-11-09
  • 2013-05-08
  • 2013-09-22
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
相关资源
最近更新 更多