Subodh Bisht
Subodh Bisht

Reputation: 899

How to get the id dropdown list on click event

This is my jspPage.

<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>    
<option id="2">Supervisor</option>
</select>

And here is javascript

 function Class(str)
{
    alert(str);
}

i want to get the id of Option on onchange Event. Thanks :)

Upvotes: 0

Views: 13443

Answers (4)

Uniquedesign
Uniquedesign

Reputation: 453

Use selsectedIndex Property of GetElementByID

<script>
    function val() {
        d = document.getElementById("select_id").selectedIndex;
    
        alert(d);
    }
    </script>
 <select onchange="val()" id="select_id">

Upvotes: 0

ElLocoCocoLoco
ElLocoCocoLoco

Reputation: 385

HTML (you should use "value" attribute instead of "id")

<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>    
<option id="2" value="ID2">Supervisor</option>
</select>

JS

var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
    alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
    alert(selectElement.selectedIndex);                           // index starting from 0
    alert(selectElement.value);                                   // value of the selected element
};

Fiddle

Upvotes: 1

mohkhan
mohkhan

Reputation: 12325

You can do this if you are trying to get the id of the option which has been selected

function Class(str)
{
    var select = document.getElementById("class_Teacher");
    var option = select.options[select.selectedIndex];
    alert(option.id);
}

Upvotes: 4

Mark Walters
Mark Walters

Reputation: 12400

Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option

onchange="myFunction(this)"

and your javascript function like this, which will alert the ID of the selected option

function myFunction(ele){
   alert(ele.options[ele.selectedIndex].id);
}

Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.

Upvotes: 1

Related Questions