So I've run into a strange issue... I want to grab the id of a form say:
<form id="test">
<input name="id" type="hidden" value/>
</form>
But running document.getElementById("test").id
doesn't return test
as expected but instead returns the input with the name="id"
. Anyone know what is going on here?
Here's a fiddle reproducing the issue -> http://jsfiddle.net/jascbbfu/
Form control names are used to create named properties of the form that reference the control. So where you have:
<form id="test">
<input name="id">
</form>
then the form's id property is assigned a reference to the input element named id. Form controls should never be given names that are the same as standard form properties, e.g. in the following:
<form>
<input name="submit">
</form>
it is impossible to call the form's submit method because form.submit references the input, not the method.
As noted in other answers, you can either change the name to something that doesn't clash with standard form properties, or use getAttribute. The first solution is preferred as it will also likely lead to more suitable names for the form controls and avoid the use of getAttribute.
What happens here is an old artifact from the times when HTML was just getting formalised. It's supposed to sit only under a named collection, but browsers decided to create shortcut access in various random places. Either way, you can read more here: http://jibbering.com/faq/notes/form-access/ And once I am on my desktop I will quote the relevant parts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With