Last Updated: 27 Jun 2023
ID vs. Name in Form Fields
When creating a form field, you should give them both an id
and a name
:
<form> <input type='text' id='formField1' name='formField1' /> <input type='text' id='formField2' name='formField2' /> </form>
This is because browsers use the name
field when they submit to a server, but when working with JavaScript it's best to use id
(and the associated document.getElementById()
) to identify elements. You could use something like document.getElementsByName()
, but it is a lot harder to work with, because names aren't guaranteed to be unique and thus that function returns a collection of elements, not just one.
You should also always name your name
and id
the same thing (and not reuse that identifier anywhere else), because of IE's poor implementation of getElementById()
which can sometimes return an element whose 'name' matches the 'id' you asked for.
Conclusion? Always use both, make them the same string, and make that string unique in the document.
Discussion