2017-04-03 3 views
1

HTML 표jQuery를 선택 2 드롭 다운

행 # 1에 대한 모든 드롭 다운 값 문제를 얻을 수 있습니다 : 골 1 [Country DropDown] | 골 2 [StateDropDown]

행 2 : 1 [Country DropDown] | 골 2 [StateDropDown]

Country & State를 들어, 2 dropdownlists이있다 -이 하나의 드롭 다운, 에 작동하지만 그뿐만 아니라 기타/상태 드롭 다운을 해제!

문제는 모두 미국과 아우 스트는 diff states selected 텍스트가 동안이지만,와 col2 endup에 같은 선택 State ID/값 3 (I 캘리포니아를 선택하면, 퍼스 따라서 내 코드가 비활성화됩니다!, 장애인도 그것들은 텍스트가 아닌 선택된 값을 비교 한 이후로 중복 된 것입니다.) 예를 들어 이 선택은 퍼스 ..

[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 (반 구운 느낌) ('옵션 [값 ='+ selectedValue + ']'). '(소품 무능한 ', 진실한); }});


<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> 


*** 이미지 유사한 ... 정확하지 뭔가를 보여

Sample to show - prevent duplicate Combinations of the Cascading drowpdowns


+0

나는 뭔가있는 것 같아.하지만 너무 멀리 가기 전에 : 나는 무엇이 동적으로 만들어 졌는지 알아야 할 것입니다. 지금까지는 첫 번째 열 (국가)이 동적이 아니라고 가정했습니다 ... 그리고 두 번째 열의 분명히 동적 인 옵션을 잊어 버렸습니다. (웃음)하지만 나는 어떤 식 으로든하고 있습니다. 나는 내일 다시 점검 할 것이다. 이것은 힘든 일입니다! –

+0

@LouysPatriceBessette 새 행이 동적으로 복제/추가 될 때 - 행이 테이블에 추가 될 때 '1)'두 가지 경우에 비활성화됨을 설정할 수 없습니다. 와'2)'첫 실행시 추가로 현재'$ this dropdown' 상태 또는 국가에서 비활성화를 설정할 수 없습니다. * 그 페이지에있는 모든 (http://stackoverflow.com/a/27145521/6085193) 조합을 수집하고 동일한 조합 값을 방지하는 것이 더 쉬운 지 궁금합니다 * – transformer

+0

당신이 기울임 꼴로 쓴 내용 : 정확히 무엇입니까? 나는에있어 ... –

답변

1

목 당신이 복사/붙여 넣기를 할 수있는 완벽한 솔루션이 아니지만, 당신이 원하는 바로는 거의 다가 가고 있습니다.바람직 바람직 class

  • 숨겨진 table 복제 할 바람직

    1. 실물 table, id
    2. td, id :

      는 I 4 개 인수 전체 함수로 만들어

    3. 새로운 행 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 
    
  • +0

    이것에 총을 줘서 고마워. 그래, 나도 알아. * 그런 간단한 문제는 내가 너무 곤란 해했다. :) 나는 당신의 샘플에서도 똑같은 문제를 안고있다. (https://ibb.co/dbH6wF) 나는 그림을 붙였다. 나는 가지고있다. upvoted 당신, 그것의 가까운 ... 그러나 나는 아직도 그것을 필요로한다. .. 그것에 관해 가야하는지 명확히하지 마라! – transformer

    +0

    내가보기 ... 당신이 보여주는 것은 정확히 내가 떠난 "버그"입니다. 이는 같은 국가에서 이미 선택되어있는 국가 선택에서 장애 조치가 두 가지 방법으로 이루어지기 때문입니다. 상태 select에서 2-를 선택하면 다른 select (및 같은 국가)에서 선택한 옵션이 비활성화됩니다. 이제 국가를 바꿀 때 선택을 다시 설정하지 않습니다 ... 그 옵션 요소를 동적으로 변경해야하기 때문에. 그래서 그것이 내가 멈춘 곳입니다. –

    +0

    여기에 좋은 링크가 [양쪽 값을 얻는] (http://jsfiddle.net/nooberz/Lr5pq/327/) ... – transformer