【问题标题】:jQuery Chosen: how to limit the number of selected values and provide an error messagejQuery Chosen:如何限制选定值的数量并提供错误消息
【发布时间】:2012-03-05 15:04:35
【问题描述】:

我正在为 2 个<select> 元素使用 jQuery Chosen。每个元素都包含相同的值,我使用循环将选定的值放入数组中,并禁用已放入该数组且不是选定选项的每个值。换句话说:我总是禁用分身。

我试图通过使用数据属性“maxpersons”来限制最后一个循环的选定值的数量,并将其与选定值的数量进行比较。

很遗憾,这仅适用于未预先选择选项。如果是的话,仍然有人可以再选择一个值。这是不允许的。

另外,我想在达到最大值时在 <select> 元素旁边放置一个 <p> 标记,并在尚未达到最大值时自动将其删除。

任何帮助将不胜感激!这是 JS 小提琴:http://jsfiddle.net/dq97z/28/

【问题讨论】:

    标签: jquery select limit option


    【解决方案1】:

    您可以将您在 change() 事件中使用的相同代码放入 document.ready() 事件中。像这样,

    $(document).ready(function(){
        var selected = [];
        var chosen='.chzn-select';
        $(chosen).parent().parent().find("option")
          .each(function () {
            if (chosen.selected) {
              selected[chosen.value] = this;
            }
          })
          .each(function () {
            this.disabled = selected[this.value] && selected[this.value] !== chosen;
          })
          .each(function () {
            if ($(this).parent().data('maxpersons') === $(this).parent().find('option:selected').length) {
              $(this).parent().find('option:not(:selected)').prop('disabled', true);
            }
          });
        $('.chzn-select').trigger("liszt:updated");
    })

    感谢代码 sn-p...!

    【讨论】:

    • 投票需要 15 声望,对不起,伙计,当我获得声望时,我一定会这样做...:)
    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    相关资源
    最近更新 更多