0

I have been searching for a way to get the id from a drop-down list option, when it is selected. I have found the following: Get selected text from a drop-down list (select box) using jQuery
And tried to change the accepted answer to:

$("#yourdropdownid option:selected").id;

But when I alert() it, it gives me "undefined". Is there a way to get the id using JQuery?

Community
  • 1
  • 1
Julian Avar
  • 476
  • 1
  • 5
  • 24
  • 2
    `$("#yourdropdownid option:selected").attr('id')` – Mr_Green May 11 '15 at 05:07
  • @Mr_Green Isn't that the same as what I wrote? isn't `.id` the same as `.attr('id')`? – Julian Avar May 11 '15 at 05:10
  • @julianavar nope.. there is difference. always use console to check whether you doing it correct or not. :) – Mr_Green May 11 '15 at 05:11
  • @julianavar. Its not same. you are using [jQuery](http://api.jquery.com/attr/) style and not pure [Javascript](http://www.w3schools.com/jsref/prop_html_id.asp) style. – Zee May 11 '15 at 05:12
  • @julianavar Don't get confuse between jquery's object and javascript's DOM object. – Mr_Green May 11 '15 at 05:16

2 Answers2

5

Because $("#yourdropdownid option:selected") returns a jQuery object which does not have the id property so, you can use .attr() to get id of the element

$("#yourdropdownid option:selected").attr('id');
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • @julianavar `$("#yourdropdownid option:selected")` is a jQuery object which does not have the `id` property, but the selected `option` element have the `id`(as far as I understood that exists and OP wants that value).... – Arun P Johny May 11 '15 at 05:15
2

Get the id using .attr() or .prop():

$("#yourdropdownid option:selected").prop('id')

or

$("#yourdropdownid option:selected").attr('id')

and if you want to use pure javascript then:

var obj=document.getElementById("myId").options[document.getElementById("myId").selectedIndex];
alert(obj.id);

Don't mix the jquery object with js property like $("#yourdropdownid option:selected").id.

Brijesh Bhatt
  • 3,810
  • 3
  • 18
  • 34