2010-10-19 137 views
0

我需要創建一個接口,選擇父多重選擇時,它會更新子選項的多選。它的目的是父母多重選擇可以沒有,選擇一個或多個選項,並且子元素顯示父母雙方都擁有的項目(或回退到所有項目)的聯合。限制兒童多選擇基於jQuery的父母的多個選擇

採取例如:

  • 當選擇父1,對於父1所有狀態項應該被允許來選擇
  • 當父1和親本2被選擇所允許之內的所有的狀態項兩家母公司1和2應該被允許在子元素

要選擇在這裏尋找四周,做了很多的谷歌搜索我想我走得很近後,但是這種解決方案很遺憾不能完全滿足第二個要求。

我可能會接近完全錯誤的方式,所以我願意接受建議。

的JS:

$(document).ready(function(){ 

var allOptions = $('#children option').clone(); 

function children_update() { 
    $('#parents > option:selected').each(function() { 
     $('#children').html(allOptions.filter('.option-' + parseInt($(this).val())));  
    }); 
    if(!$('#parents > option:selected').length) { $('#children').html(allOptions); } 
} 

children_update(); 

$('#parents').change(function() { children_update(); }); 
}); 

的HTML

Parents<br /> 
<select multiple name="parents[]" id="parents"> 
<option value="1">parent 1</option> 
<option value="2">parent 2</option> 
<option value="3">parent 3</option> 
</select> 

<br /> 
Children<br /> 
<select multiple name="children[]" id="children"> 
<option value="1" class="option-1">child 1 (1)</option> 
<option value="2" class="option-1 option-2">child 2 (1,2)</option> 
<option value="3" class="option-1 option-2 option-3">child 3 (1,2,3)</option> 
<option value="4" class="option-1 option-2">child 4 (1,2)</option> 
<option value="5" class="option-2">child 5 (2)</option> 
<option value="6" class="option-3">child 6 (3)</option> 
</select> 

感謝

回答

0

如何改變children_update功能,這...

function children_update() { 
    $("#children option").attr('disabled','true'); //start off with all disabled 
    $('#parents > option:selected').each(function() { 
     var num = $(this).val(); 
     $("#children .option-"+num).attr('disabled','false'); 
    }); 
    if(!$('#parents > option:selected').length){   //if no parents selected 
     $("#children option").attr('disabled','false'); //enable all options 
    } 
} 

如果我的理解問題糾正真的,應該有效。但是,如果你正在做一個更嚴格的組合事物(比如只顯示與父選項的確切組合相匹配的子選項),請隨時糾正我。

編輯:

好,這是一個新的解決方案:

function children_update() { 
    $("#children option").attr('disabled','true'); //start off with all disabled 
    var selectors = getSelectors(); 
    $("#children option"+selectors).attr('disabled','false'); 
} 

function getSelectors(){ 
    var parents = $("#parents").val(); 
    var selectors = ""; 
    if (parents){ 
     $.each(parents, function(index, val){ 
      selectors = selectors + ".option-" + val; 
     }); 
    } 
    return selectors; 
} 
+0

感謝您的建議,這是一個嚴格的匹配來完成要求:只顯示由所有選擇匹配的子選項父母選擇。可能需要採取不同的方法?很高興聽到你有任何想法。 – 2010-10-20 00:10:17

+0

這樣正確理解這一點... 如果僅選擇了父項1:只有子項1將被啓用。 如果選擇父母1和2:僅啓用子女2和4。 如果選擇父母1和2和3:只有孩子3將被啓用。 這是你打算的計劃嗎? – 2010-10-20 02:37:22

+0

對不起,我一開始並不清楚,但是是的,這就是我要去做的。父母的任何組合都將禁用/啓用他們各自的子元素。 – 2010-10-20 03:27:35