2013-05-29 54 views
2

我已經合衆國(USA),其中包括加拿大各省的名單,更新選擇菜單關閉另一個選擇

<select> 
<optgroup label="United States"> 
    <option value="AL">Alabama (AL)</option><option value="AK">Alaska (AK)</option><option value="AE">APO state (AE)</option><option value="AO">APO state (AO)</option><option value="AP">APO state (AP)</option><option value="AZ">Arizona (AZ)</option> 
</optgroup> 
<optgroup label="Canada"> 
<option value="AB">Alberta (AB)</option><option value="BC">British Columbia (BC)</option><option value="MB">Manitoba (MB)</option><option value="NB">New Brunswick (NB)</option><option value="NL">Newfoundland and Labrador (NL)</option></optgroup> 
</select> 

然後我還有一個選擇菜單,其中包括2個選擇,美國&加拿大。 (美國是默認選擇)

我希望如果選擇加拿大省,在第二選擇菜單中禁用美國爲國家。如果在第二個選擇菜單中選擇了加拿大,則從第一個選擇菜單中移除USA狀態。

我只找到方法來填充第二個選擇菜單後(如http://jsfiddle.net/FK7ga/),但我的嘗試是默認情況下顯示所有,並在選擇任何一個後更新。

+0

@ j08691見下文http://stackoverflow.com/a/16822289/1058222 – Joel

回答

1

你可以做這樣的事情:

$("#filter").on("change", function() { 
    $states = $("#states"); 
    $states.find("optgroup").hide().children().hide(); 
    $states.find("optgroup[label='" + this.value + "']").show().children().show(); 
    $states.find("optgroup[label='" + this.value + "'] option").eq(0).prop("selected", true); 
}); 

See this working DEMO

1

@letiagoalves:

我只是通過改變show/hideattr('disable','disable');removeAttr('disable');編輯您的提琴這將導致列表留下,但防止錯誤的國家組被選中。

只是我2美分。

1

之所以能夠使其工作,因爲我想,隨着@letiagoalves的幫助,下面是代碼

$("#countries").on("change", function() 
{ 
    if ($("#countries").find(":selected").val()) 
    { 
     $states = $("#states"); 
     $states.find("optgroup").hide().children().hide(); 
     $states.find("optgroup[label='" + this.value + "']").show().children().show(); 
     $states.find("optgroup[label='" + this.value + "'] option").eq(0).prop("selected", true); 
    } 
    else 
    { 
     $states.show().children().show().children().show(); 
    } 
}); 

$("#states").on("change", function() { 
    $countries = $("#countries"); 

    if ($("#states").find("option:selected")) 
    { 
     var c = $("#states").find("option:selected").parent().attr("label"); 
     $countries.find("option[value='" + c + "']").prop("selected", true); 
     $("#countries").change(); 
    } 
}); 

仍在試圖使其與禁用@Alex-Amthor's idea工作,如果我成功,將更新的答案。同時這裏是一個demo on jsfiddle

相關問題