2017-04-26 65 views
1

我正在使用Web2Py向我的視圖發送值列表。Javascript如何獲取所選項目的ID

我的HTML是這樣的:

<select id="DestinationOptions" onchange="SetDest(this)"> 
    {{for key, value in dirList.iteritems():}} 
     <option name="DirListItem{{=key}}" id="{{=key}}"> {{=value}}</option> 
    {{pass}} 
</select> 

我的JavaScript是這樣的:

function SetDest(destComboBxID) 
{ 
    alert(destComboBxID.id); 
    var e = document.getElementById(destComboBxID); 
    var path = e.option[e.selectedIndex].value; 
    alert(path); 
    //document.cookie = "GD_"+file.id + "=" + file.id + ";"; 
} 

我只得到的第一alert(),然後我得到以下錯誤,當我在調試布勞爾:

Uncaught TypeError: Cannot read property 'options' of null

Q :我如何獲得選定值的ID?

+0

記:你的'template'是這樣的,不'HTML' –

+0

取代'變種E =的document.getElementById(destComboBxID);'和'變種E = destComboBxID;' –

+0

如果它不是HTML,你會怎麼稱呼它?它來自一個* .html文件... – fifamaniac04

回答

2

您可以將EventListener添加到選擇字段。當它改變時,您可以使用e.target.options[e.target.selectedIndex].getAttribute('id')獲得所選選項的ID。

document.getElementById('DestinationOptions').addEventListener('change', function(e) { 
 
    console.log(e.target.options[e.target.selectedIndex].getAttribute('id')); 
 
});
<select id="DestinationOptions"> 
 
    <option id="1">Hello</option> 
 
    <option id="2">World</option> 
 
</select>

0
<select id="DestinationOptions" ="SetDest(this.id)"> 
+0

所以我認爲如果代碼使用(this)關鍵字只有它會返回對象指的是選擇不是它是ID然後在他使用它作爲ID的功能,所以我認爲解決方案是使用(this.id)。 – Osama