views:

2602

answers:

6

Hi guys what is the difference between the id and name attributes? they both seem to serve the same purpose of providing an identifier.

I would like to know (specifically with regards to ASP.net web forms) whether or not using both is necessary or encouraged for any reasons.

Thanks guys!

+12  A: 

The name is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different ids, but the same name. When submitted, there is just the one value in the response - the radio button you selected.

Of course, there's more to it than that, but it will definitely get you thinking in the right direction.

John Fisher
+5  A: 

Use name attributes for <form> elements, as that's the identifier used in the POST or GET call that happens on form submission.

Use id attributes whenever you need to address a particular element with CSS or JavaScript. It's possible to look up elements by name, too, but it's more efficient to look them up by ID.

Warren Young
AFAIK, the `<form>`s name attribute is not sent with the data.
nickf
Form **controls** (like input and select elements) not form elements.
David Dorward
+3  A: 

Id is used to identify the HTML element through the Document Object Model (via Javascript or styled with CSS). Id is expected to be unique within the page.

Name corresponds to the form element and identifies what is posted back to the server.

Mike Buckbee
+1  A: 

This link has answers to the same basic question, but basically, id is used for scripting identification and name is for server-side.

http://www.velocityreviews.com/forums/t115115-id-vs-name-attribute-for-html-controls.html

James Black
+2  A: 

ID tag - used by CSS, define a unique instance of a div, span or other elements. Appears within the Javascript DOM model, allowing you to access them with various function calls.

Name tag for fields - This is unique per form -- unless you are doing an array which you want to pass to PHP/server-side processing. You can access it via Javascript by name, but I think that it does not appear as a node in the DOM or some restrictions may apply (you cannot use .innerHTML, for example, if I recall correctly).

Extrakun
radio buttons *must* share the same name to behave properly - it's not unique per form.
nickf
My mistake. Though to clarify, for text inputs, text areas and etc, name tags are used to identify them. Not necessary unique.
Extrakun
A: 

I thing id refers to instance of a control like in java everything is class if v call an element by its id means v refer 2 instance of that element whereas name refers just name of the element.

Ismail