【问题标题】:Jquery selector to get all dropdown values, issues for 2 dropdownsJquery 选择器获取所有下拉列表值,2 个下拉列表的问题
【发布时间】:2017-04-03 19:38:50
【问题描述】:

HTML 表格

第 1 行:第 1 列 [Country DropDown] | Col #2 [StateDropDown]

第 2 行:第 1 列 [Country DropDown] | Col 2 [StateDropDown]

表格有 2 个dropdownlists,用于CountryState - 这适用于一个下拉菜单,但它也禁用其他/状态下拉菜单!

问题是,虽然 USA 和 Aust 都有 diff states selected 文本,但在 col2 最终选择了 same State ID/value 3 (如果我选择加利福尼亚,珀斯也被禁用!,因此我的代码将它们作为重复项禁用,因为它比较选定的值而不是文本),例如此选择禁用珀斯..

[USA]      ->    [California]  (value = 3)
[Australia] ->   [Perth]       (*also* has value= 3) so its disabled

如何以unique combination 的身份在每行中同时显示国家和州?还是只是比较下拉菜单的文本?...

  1. 即选项1,如何同时检查Country ID + State ID Value already exist
  2. 选项2,只比较选定的文本(感觉半生不熟)

JS Fiddle

// Javascript Does not disable States previously selected
$("#CountryTable").on('change', '.State', function() {
var dropDownText = $('#CountryTable .State select').not(this).map(function()                {
 return this.SelectedText; // does not work this.val() works but useless
}).get();
var selectedValue = $(this).val();
var otherDropdowns = $('.State').not(this);

otherDropdowns.find('option[value=' + selectedValue + ']').prop('disabled', true); });


<table id="CountryTable">
<tbody id="CountryTableBody"> 
    <tr class="row">
        <td>
            <select>
                <option value="1">Country A</option>
                <option value="2">Country B</option>
                <option value="3">Country C</option>
            </select>               
        </td>

        <td>
            <select>
                <option value="1">State 1</option>
                <option value="2">State 2</option>
                <option value="3">State 3</option>
                <option value="4">State 4</option>
                <option value="5">State 5</option>
            </select>               
        </td>           
    <tr>  <!-- in JS prevent previous selection -->
    <tr class="row">
       <td>
            <select>
                <option value="1">Country A</option>
                <option value="2">Country B</option>
                <option value="3">Country C</option>
            </select>               
        </td>
        <td>
            <select>
                <option value="1">State 1</option>
                <option value="2">State 2</option>
                <option value="3">State 3</option>
                <option value="4">State 4</option>
                <option value="5">State 5</option>
            </select>               
        </td>          
    <tr>    
</tbody>   


*** 图片显示相似...不准确


【问题讨论】:

  • 我想我正在做一些事情......但在走得太远之前:我需要知道什么是动态创建的。到目前为止,我假设第一列(国家)不是动态的......我忘记了第二列的明显动态选项。 (大声笑)但无论如何我都在做某事。我明天再检查一次。这是一个艰难的!
  • @LouysPatriceBessette 我无法在两种情况下设置禁用 - 1) 当新行被动态克隆/附加时 - 当这些行被附加到表中时。和2) 另外在第一次运行时,我无法在当前的“$this dropdown”州或国家/地区设置禁用。 我想知道是否更容易在页面上collect all the组合,并防止相同的组合值
  • 你用斜体写的:正是我在写的......

标签: javascript jquery html drop-down-menu dropdown


【解决方案1】:

这不是一个完美的解决方案,您可以复制/粘贴,但它已经非常接近您想要的。

我用 4 个参数将它作为一个完整的函数:

  1. 真正的table,最好是id
  2. td,最好是class
  3. 要克隆的隐藏table,最好是id
  4. 新行button,最好是id

让您可以在 HTML 中随意命名您想要的东西,而不用关心修复脚本中使用这 4 个的多个位置。

现在...这只是一个好的开始。
事实上,当用户从“A国”切换到“B国”时,状态下拉菜单应该是不同的!

这是我留下的唯一问题...因为我不知道你想如何加载这些选项。

我花了很长时间才放弃...我之所以这样做是因为我无法相信这样一个“简单”的请求会如此复杂...我不得不粉碎它
;)。

这里是代码(仅限 JS)和一个有效的 CodePen 演示。

var excusiveSelect = function(tableID,rowCLASS,dummyID,cloneBtn){   // Preferably ID, CLASS, ID, ID

  console.clear();

  // Cloning function
  var cloneRow = function(){
    var newrow = $(dummyID).find(rowCLASS).clone();
    $(tableID).append(newrow);
    refresh_mapping();
  };

  // Generate new lines
  $(cloneBtn).on("click",cloneRow);

  // ================================================================================ INITIALISATION
  // Selection mapping
  var row_count;
  var row_map = {};

  // Get select clas names per colums
  var col_count = $(rowCLASS).first().find("td").length;
  var col_classes = [];
  for(i=0;i<col_count;i++){
    col_classes[i] = $(document).find(rowCLASS).first().find("select").eq(i).attr("class").split(" ").join(".");
  }
  console.log("SELECT CLASSES: "+JSON.stringify(col_classes));

  var refresh_mapping = function(){
    row_count =  $(document).find(rowCLASS).length-1;
    console.log("ROWCOUNT: "+row_count);
    for(i=0;i<row_count;i++){

      row_map["row_"+i] = {};
      $(tableID).find(rowCLASS).eq(i).find("select").each(function(index){

        // Get the select classes as object attribute.
        var thisClasses = $(this).attr("class").split(" ").join(".");

        // For each row/select get the selected index.
        row_map["row_"+i][thisClasses] = $(this)[0].selectedIndex;
      });
    }
    console.log("VALUES MAPPING: "+JSON.stringify(row_map));
  }

  cloneRow();

  // ================================================================================ FROM COLUMN #1

  $(document).on("change","."+col_classes[0],function(){
    console.log("\n======================================================= Country change\n");

    refresh_mapping();

    // Disables options already selected in ALL col_classes[1] where col_classes[0] is the same
    for(i=0;i<row_count;i++){

      if( ( row_map["row_"+i][col_classes[0]] == $(this)[0].selectedIndex ) 
         && (  $(this).closest(rowCLASS).index() != i ) ){

        $(this).closest(rowCLASS).find("."+col_classes[1]+" option").eq( row_map["row_"+i][col_classes[1]] ).attr("disabled",true);

        // Else enable the option if not self
      }else{
        if( $(this).closest(rowCLASS).index() != i ){
          $(this).closest(rowCLASS).find("."+col_classes[1]+" option").eq(i).attr("disabled",false);
        }
      }
    }

  });

  // ================================================================================ FROM COLUMN #2

  $(document).on("change","."+col_classes[1],function(){
    console.log("\n======================================================= State change\n");
    console.clear();
    refresh_mapping();

    thisIndex = $(this)[0].selectedIndex;               // Option selectedIndex
    thisRowIndex = $(this).closest(rowCLASS).index();     // Row index

    // If same country...
    var thisCol0index = $(this).closest(rowCLASS).find("."+col_classes[0])[0].selectedIndex;


    $(tableID).find("."+col_classes[1]).each(function(){
      if( $(this).closest(rowCLASS).find("."+col_classes[0])[0].selectedIndex == thisCol0index ){

        // Zap tout les disabled
        $(this).find("option:not(:eq(0))").attr("disabled",false);

        // Use mapping to disable based on col_classes[0]
        for(i=0;i<row_count;i++){
          if( row_map["row_"+i][col_classes[0]] == thisCol0index ){

            $(this).find("option").eq(row_map["row_"+i][col_classes[1]]).attr("disabled",true);
          }
        }

      }
    });
  });
  // ================================================================================
}

// Init!
excusiveSelect("#CountryTable",".row","#DummyTable","#newRow");   // Preferably ID, CLASS, ID, ID

【讨论】:

  • 感谢您对此进行尝试。是的,我知道是对的,这么简单的问题也让我难过 :) 我在your sample too 中出现了同样的问题。我附上了图片.. 我给你投票了,很接近...但我仍然需要解决方案...不知道该怎么做!
  • 我明白了......你展示的正是我留下的“错误”。这是因为禁用是通过两种方式进行的 1- 从国家选择中检查是否已为同一国家/地区选择。 2-从州选择,这会禁用其他选择(和同一国家)中的选定选项。现在,当您更改国家/地区时,它不会重置选择...因为它应该动态更改这些选项元素。所以这就是我停下来的地方。
  • 这里有一个很好的链接到getting both values...
猜你喜欢
  • 2011-07-06
  • 2018-12-21
  • 2020-03-04
  • 2013-01-12
  • 2013-10-06
  • 2015-12-30
  • 1970-01-01
  • 2013-02-25
  • 1970-01-01
相关资源
最近更新 更多