Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab id of a form that has a child input with a name="id"

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/

like image 729
Jake Zieve Avatar asked Feb 06 '15 00:02

Jake Zieve


2 Answers

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.

like image 191
RobG Avatar answered Nov 14 '22 07:11

RobG


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.

like image 33
David Mulder Avatar answered Nov 14 '22 07:11

David Mulder