Last Updated: 27 Jun 2023

   |   

Author: dordal

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Last revision Both sides next revision
front-end-tech:xhtml:id-vs.-name-in-form-fields [May 24, 2008 01:05 AM]
dordal
front-end-tech:xhtml:id-vs.-name-in-form-fields [Jun 25, 2023 07:25 PM]
110.249.202.42 removed
Line 1: Line 1:
 += ID vs. Name in Form Fields =
  
 +When creating a form field, you should give them both an ''id'' and a ''name'':
 +<code html>
 +<form>
 +<input type='text' id='formField1' name='formField1' />
 +<input type='text' id='formField2' name='formField2' />
 +</form>
 +</code>
 +
 +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 [[http://www.456bereastreet.com/archive/200802/beware_of_id_and_name_attribute_mixups_when_using_getelementbyid_in_internet_explorer/|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.**