2012-08-09 65 views
0

我試圖根據用戶輸入從選擇下拉框中顯示/隱藏各種div。實際上,首先,我試圖直接實施jQuery dropdown hide show div based on value中顯示的代碼,但是我錯過了一些簡單的東西,它可以防止它在http://www.intertwineimages.com/form2.html的工作,這裏是我的完整代碼,任何人都可以指出我的方向嗎?jquery show/hid div基於下拉

<html> 

<script type="text/javascript"> 
hideAllDivs = function() { 
    $("#hourly").hide(); 
    $("#per_diem").hide(); 
    $("#fixed").hide(); 
}; 

handleNewSelection = function() { 

    hideAllDivs(); 

    switch ($(this).val()) { 
     case '1': 
      $("#hourly").show(); 
     break; 
     case '2': 
      $("#per_diem").show(); 
     break; 
     case '3': 
      $("#fixed").show(); 
     break; 
    } 
}; 

$(document).ready(function() { 

    $("#project_billing_code_id").change(handleNewSelection); 

    // Run the event handler once now to ensure everything is as it should be 
    handleNewSelection.apply($("#project_billing_code_id")); 

}); 
</script> 
<select id="project_billing_code_id"> 
    <option value="">Pick one</option> 
    <option value="1">1-Hourly</option> 
    <option value="2">2-Per Diem</option> 
    <option value="3">3-Fixed</option> 
</select> 

<div id="hourly">Hourly</div> 
<div id="per_diem">Per Diem</div> 
<div id="fixed">Fixed</div> 

</html> 

編輯:糾正代碼

<html> 

<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript"> 
hideAllDivs = function() { 
    $("#hourly").hide(); 
    $("#per_diem").hide(); 
    $("#fixed").hide(); 
}; 

handleNewSelection = function() { 

    hideAllDivs(); 

    switch ($(this).val()) { 
     case '1': 
      $("#hourly").show(); 
     break; 
     case '2': 
      $("#per_diem").show(); 
     break; 
     case '3': 
      $("#fixed").show(); 
     break; 
    } 
}; 

$(document).ready(function() { 

    $("#project_billing_code_id").change(handleNewSelection); 

    // Run the event handler once now to ensure everything is as it should be 
    handleNewSelection.apply($("#project_billing_code_id")); 

}); 
</script> 
<select id="project_billing_code_id"> 
    <option value="">Pick one</option> 
    <option value="1">1-Hourly</option> 
    <option value="2">2-Per Diem</option> 
    <option value="3">3-Fixed</option> 
</select> 

<div id="hourly">Hourly</div> 
<div id="per_diem">Per Diem</div> 
<div id="fixed">Fixed</div> 

</html> 
+0

jQuery的文件,那麼它似乎工作。演示http://jsfiddle.net/qzSu6/。順便說一句,你有沒有包含jquery js文件? – 2012-08-09 13:36:29

+0

沒錯,它在jsfiddle上工作,但我無法讓它在我的服務器上工作(http://www.intertwineimages.com/form2.html),想知道爲什麼它不會。 – Constantino 2012-08-09 13:37:24

+0

我給你的建議是徹底拋棄jQuery並學習如何使用真正的JavaScript。 – John 2012-08-09 13:38:17

回答

2

它,因爲你還沒有爲http://www.intertwineimages.com/form2.html

+0

啊!這是我錯過的簡單的事情。你能告訴我究竟如何做到這一點或闡明這個問題? – Constantino 2012-08-09 13:40:34

+0

http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery – hsalama 2012-08-09 13:41:51

+0

它很簡單。我的firefox上安裝了firebug。當我打開網址時,我在螢火蟲中發現一個錯誤,提示'$未定義'。 – 2012-08-09 13:41:52