如何防止在选定的jQuery多选时一行重复条目

How do I prevent duplicate entries in a row at chosen jQuery multiple select?

本文关键字:一行 何防止 jQuery      更新时间:2023-09-26

我有几行,几乎没有选择框。每行中有几个具有相同内容的选择框。行中的每个项目只能使用一次,因为每列都有一个分类。如果在选择框中使用某个项目,我希望它在行的其他框中显示为灰色。我试过这个:

  function setChosen() {
    var config = {
  '.chosen-select' : {},
  '.chosen-select-deselect': {allow_single_deselect:true},
  '.chosen-select-no-single' : {disable_search_threshold:10},
  '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
  '.chosen-select-width' : {width:'95%'}
    }
    for(var selector in config) {
    $(selector).chosen(config[selector]);
  }
 }
 setChosen();
 $('.chosen-select').on('change', function() {
   var selVal = $(this).val();
   var rel = $(this).attr('rel');
   $('.'+rel).children('option').each(function() {
    if($(this).val() == selVal) {
      $(this).attr('disabled',true).siblings().removeAttr('disabled').trigger('chosen:updated');
  }
 });
});

小提琴

我会这样做:

从触发onchange事件的选择中,我们可以在 DOM 中使用 jQuery 的 parent() 向上移动到它的父级。然后选择该父级中的所有select元素。循环访问每个选择。首先将选项重置回 enabled ,最后禁用与触发事件的选择的选定值匹配的选项。

 $('.chosen-select').on('change', function() {
    var self = this; //create a reference to the owner of the event.
    var selVal = $(this).val(); //selected value
    var parent = $(this).parent(); //select parent row
    //traverse all children in that row that are selects
    parent.children('select').each(function() {
        $(this).find("option").attr("disabled", false); //set all disabled attributes to false. Basically a reset!
        if (this != self) //skip the select that is the owner of the event
        {
           //set the other options to disabled that matches the value of the select.
           $(this).find("option[value='"+selVal+"']").attr("disabled", true);
        }
    });
});