01-04-2007, 05:53 PM
I am aware that it is possible to access form elements by their ID e.g.
However is there a way to return the name of an element and store it in a variable?
For example I have a list box and on selecting an option, I would like to display the ID of that option. Any help would be appreciated.
01-04-2007, 07:57 PM
Options within a select list are distinguished by their <b>value</b> and <b>text</b>. The options are just a part of the select and not separate elements and those are the only two properties that are defined as arrays rather than individual fields.
01-04-2007, 08:42 PM
In this case, document.getElementById won't work, just as felgall said before.
But there is another way for you to get the ID of an option.
You can put anything you want in the tags of any element.
if you write <inptu type="button" id="X" VaRiAbLe="This is a variable" />, alert(document.getElementById("X").VaRiAbLe) will return "This is a variable".
With options you can't do this, but you can access an option that can have a specific id just making a loop throughout the <select> tag.
<option id="opt2">opt 2</option>
for( var i=0; i<document.getElementById("selecao").options.length; i++)
if( document.getElementById("selecao").options[i].id == 'opt2' )
It's not the fastest way, but it will work fine.
I hope this can be useful for you. =)
01-04-2007, 10:53 PM
Of course if you add your own attributes like that then the code will not work in some browsers and it wont pass validation (unless you are using XML and define your own doctype).
01-05-2007, 04:24 PM
Hum.... I didn't get it... can you show us an example?? :)