Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how to get the ID of selected Item

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?

like image 543
fifamaniac04 Avatar asked Sep 18 '25 14:09

fifamaniac04


1 Answers

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>
like image 130
Toby Mellor Avatar answered Sep 21 '25 03:09

Toby Mellor