iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 4
2
自我挑戰組

資工的日常系列 第 4

HTML 做出2層的下拉式選單 JavaScript

HTML5用JavaScript實做下列學院與科系動態選擇頁面,以逢甲為例
https://ithelp.ithome.com.tw/upload/images/20171223/20107866Q4ndrgB8vk.png

github原碼:https://github.com/fcu-d0440478/WP-HW4.git
程式碼解說:
body裡

<form>
    <p>請選擇學院</p>
    <!--給定這id,等等需要用他填入學院資料,onchange內動到這element會呼叫裡面的方法
    this.selectedIndex是選到第幾項的值(0開始)傳入當參數-->
    <select id="college-list" onchange="changeCollege(this.selectedIndex)"></select>
    <br>
    <br>
    <p>當你選擇學院後,下列選單會列出屬於該學院的所有科系</p>
    <select id="sector-list"></select><!--給定這id,等等需要用他填入對應的系所資料-->
</form>

注意:HTML部分使用https://chart.googleapis.com/chart?cht=tx&amp;chl=%3C!--%20something%20here--%3E作註解,script部分還是用//作註解

javascript部分:

<script type="text/javascript">
    //學院的陣列
    var colleges=['商學院','工學院','建設學院','金融學院','建築專業學院','國際科技與管理學院','資電學院','人文社會學院','理學院','經營管理學院','跨領域設計學院','跨科系學習'];
    //document就是這html文件。
    //getElementById是裡面的方法,參數給"college-list"抓到這id標籤列
    var collegeSelect=document.getElementById("college-list");
    //製造一個字串,以html的語法填入院的陣列
    var inner="";
    for(var i=0;i<colleges.length;i++){
        //inner第一行就會像是 <option value=0>商學院</option>
        inner=inner+'<option value=i>'+colleges[i]+'</option>';
    }
    //innerHTML 賦值inner給這element屬性
    collegeSelect.innerHTML=inner;
    /*
    其實就是用程式碼的方式把XML文件修改成這樣
    <select id="college-list">
        <option value="0">商學院</option>
        <option value="1">工學院</option>
        <option value="2">建設學院</option>
        <option value="3">建築專業學院</option>		
        ....		
    </select>
    */
    //這裡放系所的陣列(有順序性,對應各學院的資料)
    var sectors=new Array();
    //sectors[0]=...  陣列很長,要完整的code我上面有github連結
    //動到"college-list"這select元素後呼叫此方法
    function changeCollege(index){
        //跟剛剛一樣,製造一個字串,以html的語法填入系所的陣列
        var Sinner="";
        for(var i=0;i<sectors[index].length;i++){
            Sinner=Sinner+'<option value=i>'+sectors[index][i]+'</option>';
        }
        //抓到"sector-list"這select元素,修改其值
        var sectorSelect=document.getElementById("sector-list");
        sectorSelect.innerHTML=Sinner;
    }
    //這裡呼叫一次"changeCollege"這方法,讓瀏覽器在讀完XML後可以直接讓系所的資料出來(商學院)
    changeCollege(document.getElementById("college-list").selectedIndex);
</script>

body結束

明天再來用JQuery的部分


上一篇
CPE考題 How Many Knights
下一篇
HTML 做出2層的下拉式選單 JQuery
系列文
資工的日常30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
pratbrid
iT邦新手 5 級 ‧ 2020-04-15 13:45:31

感謝邦友提供實用又清晰的範例!
有兩處需稍微更正
inner=inner+'<option value=i>'+colleges[i]+'</option>';
Sinner=Sinner+'<option value=i>'+sectors[index][i]+'</option>';
應分別修正為
inner=inner+'<option value='+i+'>'+colleges[i]+'</option>';
Sinner=Sinner+'<option value='+i+'>'+sectors[index][i]+'</option>';

已修正到Github上了,感謝回覆

我要留言

立即登入留言