最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

getelementbyid - Javascript how to get the ID of selected Item - Stack Overflow

programmeradmin2浏览0评论

I'm using Web2Py to send a list of values to my view.

My HTML is like this:

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

My javascript is like this:

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 + ";";
}

I only get the to the first alert() and then I get the following error when i debug in the brower:

Uncaught TypeError: Cannot read property 'options' of null

Q: How can I get the ID of the selcted value?

I'm using Web2Py to send a list of values to my view.

My HTML is like this:

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

My javascript is like this:

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 + ";";
}

I only get the to the first alert() and then I get the following error when i debug in the brower:

Uncaught TypeError: Cannot read property 'options' of null

Q: How can I get the ID of the selcted value?

Share Improve this question asked Apr 26, 2017 at 21:16 fifamaniac04fifamaniac04 2,38314 gold badges52 silver badges75 bronze badges 4
  • note: your template is like this, not HTML – Iłya Bursov Commented Apr 26, 2017 at 21:16
  • replace var e = document.getElementById(destComboBxID); with var e = destComboBxID; – Iłya Bursov Commented Apr 26, 2017 at 21:18
  • if it's not HTML, what would you call it? It is from a *.html file... – fifamaniac04 Commented Apr 26, 2017 at 21:25
  • it is called template, which is processed by template engine to render html, file name extension is not so important, but in this case *.html is wrong – Iłya Bursov Commented Apr 26, 2017 at 21:26
Add a ment  | 

2 Answers 2

Reset to default 5

You could add an EventListener to the select field. When it changes, you can get the ID of the selected option by using e.target.options[e.target.selectedIndex].getAttribute('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>

<select id="DestinationOptions" ="SetDest(this.id)">
发布评论

评论列表(0)

  1. 暂无评论