mongmong seesee
mongmong seesee

Reputation: 1015

How to get id name using javascript on select tag?

How to get id name using javascript on select tag ?

This is my code, when i tested it alerts undefined.

for example when i selected bbb in select tag i'll alert 2

How can i do it?

This is my fiddle

<select id="test" onchange="test_fn()">
   <option id="1" value="11">aaa</option>
   <option id="2" value="22">bbb</option>
   <option id="3" value="33">ccc</option>
</select>



<script type="text/javascript">
function test_fn()
{
    alert(this.id);
}
</script>

Upvotes: 1

Views: 3621

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

In fact you just need select.options[select.selectedIndex].id, and pass the select element as an argument to your function using this keyword.

function test_fn(select)
{
  console.log("ddd");
    alert(select.options[select.selectedIndex].id);
}
<select id="test" onchange="test_fn(this)">
<option id="1" value="11">aaa</option>
<option id="2" value="22">bbb</option>
<option id="3" value="33">ccc</option>
</select>

Upvotes: 3

Related Questions