2014-04-22 46 views
0

我正在嘗試使級聯下拉在哪些國家應該根據國家過濾,我正在嘗試很多代碼沒有什麼與我的網站一起工作,我使用的代碼之一是正確的工作,當我用它作爲一個單獨的演示測試代碼根據我的要求給結果,但是當我在我的項目中使用相同的代碼與它不工作。爲什麼不工作在我的網站這個JavaScript?

我的腳本代碼如下:

<script type="text/javascript"> 
    var country = new Array('United State','Indonesia','Thailand','Australia','Germany','Japan'); 
    var state = new Array(); 
    state["United State"] = new Array("qw", "we", "er", "rt"); 
    state["Indonesia"] = new Array("as", "sd", "df"); 
    function resetForm(theForm) { 
     /* reset country */ 
     theForm.country.options[0] = new Option("Please select a country", ""); 
     for (var i=0; i<country.length; i++) { 
     theForm.country.options[i+1] = new Option(country[i], country[i]); 
     } 
     theForm.country.options[0].selected = true; 
     /* reset state */ 
     theForm.state.options[0] = new Option("Please select a state", ""); 
     theForm.state.options[0].selected = true; 
    } 
    function updatestate(theForm) { 
     var make = theForm.country.options[theForm.country.options.selectedIndex].value; 
     var newstate = state[make]; 
     theForm.state.options.length = 0; 
     theForm.state.options[0] = new Option("Please select a state", ""); 
     for (var i=0; i<newstate.length; i++) { 
      theForm.state.options[i+1] = new Option(newstate[i], newstate[i]); 
     } 
     theForm.state.options[0].selected = true; 
    } 
</script> 

而我的HTML代碼也低於:

<form method="get" name="autoSelectForm"> 
    <div class="control-group"> 
     <label>COUNTRY<span style="font-size:13px;font-weight:normal;display:none;">(Max.2)</span></label> 
     <select name="country" size="2" style="width:100%; height:25px;" class="choseninput" id="filCountry" onchange="updatestate(this.form)"></select> 
    </div> 
    <div class="control-group"> 
     <label>STATE <span style="font-size:13px;font-weight:normal;display:none;">(Max.2)</span></label> 
     <select name="state" style="width:100%; height:25px;" class="choseninput" id="filState"></select> 
    </div> 
<form> 
+0

你能否澄清 「不工作」?它會在控制檯中拋出錯誤嗎? – jshanley

+0

沒有,沒有什麼錯誤,在下拉菜單中顯示,但counrty列表美是不是在下拉 – poonam

回答

0

你在你的Array對美國國家的額外空間。首先,你需要糾正一個

//var country = new Array('United  State','Indonesia','Thailand','Australia','Germany','Japan'); 
var country = new Array('United State','Indonesia','Thailand','Australia','Germany','Japan'); 

而你需要做的是在代碼中填充狀態options之前,你需要檢查的狀態在state陣列選定的country定義。因爲你將它們定義爲鍵,如state["United State"]state["Indonesia"],您可以使用.hasOwnProperty()的方法來檢查,如果所選擇的國家state數組作爲key存在與否。

if (!state.hasOwnProperty(make)) return; 

FIDDLE

+0

顯示我試過,但同樣的問題又來了,沒有狀態的顯示,我不明白爲什麼不能在我的特定的項目工作,效果很好在其他分區文件中。 – poonam

+0

我猜你的問題是'js'代碼位置。您需要在**相關的'html'之後放置'js'代碼**。 –

+0

我已經試過這個,但沒有解決方案,是否有任何js衝突的問題,因爲在這個項目中使用了許多其他腳本 – poonam

相關問題