jQuery Chosen:如何限制所选值的数量并提供错误消息

Mar*_*out 4 jquery select limit option

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

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

不幸的是,这只适用于尚未预先选择选项的情况.如果是,有人仍然可以再选择一个值.哪个不应该被允许.

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

任何帮助将非常感谢!这是JS小提琴:http://jsfiddle.net/dq97z/28/

Moh*_*sil 5

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

$(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");
})
Run Code Online (Sandbox Code Playgroud)

感谢您的代码片段......!