Javascript如何获取选中项的ID [英] Javascript how to get the ID of selected Item

查看:75
本文介绍了Javascript如何获取选中项的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Web2Py向我的视图发送值列表.

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

我的HTML如下:

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

我的javascript是这样的:

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

我只进入第一个 alert(),然后在浏览器中调试时得到以下错误:

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

未捕获的TypeError:无法读取null的属性选项"

问:如何获取选择值的ID?

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

推荐答案

您可以将EventListener添加到选择字段.更改后,您可以使用 e.target.options [e.target.selectedIndex] .getAttribute('id')获取所选选项的ID.

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>

这篇关于Javascript如何获取选中项的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆