• 0

[JS] Get the id of an option


Question

Hey,

So im trying to get the ID of an option from my select tags.

<select id="category" onchange="category_change()"> 
    <option id="0">Please Select A Category</option> 
    <option id="createnew">Add New Category</option> 
</select> 

I seem to be able to get whats inside the option tag, but not the actual id :(

the reason i want this value is so i can test to see if they have select the "createnew" option, so i can then display an extra input box so they can add a new category.

any ideas?

Thanks in advance

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Why are you using id and not value? Here's one way to get it:

var e = document.getElementById('category');
var val = e.options[e.options.selectedIndex].value;

If you're using a JS framework, getting the value is easier. In jQuery:

var val = $('#category').val();

Link to comment
Share on other sites

  • 0

I agree with what Mathachew said. you should be using the "value" attribute, not the ID attribute. ID attributes are designed to identify an element uniquely in your HTML page, whereas values are coded representation of an option element (which is what you want).

@Mathachew. Your JQuery wouldn't work, since it would pull back the TEXT of the selected item, and not the value (one of the stupidest decisions in JQuery's design IMO). The code you'd actually need is:

var val = $('#category :selected').val();

This finds the first option with the "selected" attribute specified, and returns the value attribute.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.