2017-04-26 14 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 :どのように私はselcted値のIDを取得できますか?

+0

注:あなた 'template'はこのようなものです、ない' HTML' –

+0

は '置き換えるVAR E =のdocument.getElementById(destComboBxID);' 'VAR電子= destComboBxIDと;' –

+0

場合それはHTMLではない、あなたはそれを何と呼ぶだろうか? * .htmlファイルからです... – fifamaniac04

答えて

2

selectフィールドに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

関連する問題