Name javascript vs ID

As far as I know, there are two ways to get a value from a text field:

document.formName.textboxName.value; 

or

 document.getElementbyId('textboxId').value; 

As I understand it, using the form name means that I have less code to write, since the name can be used to publish data and get the value (other than using ajax). How and where, if I just published using the standard form, I would use name to publish, but I can not use id ?

eg. in php i would use

 $_POST['texboxName']; 

If I have and ID in the text box, I can not get the value using php?

What is the standard recommended way to do this and uses a name friendly browser? Links, if possible, please, thanks.

+7
javascript standards xhtml
source share
5 answers

The ultimate guide to this is the HTML specification .

Things that stand out there:

  • id valid for any HTML element, and name applies only to a few ( a , input , textarea and possibly several others).
  • The input element (and textarea ) requires that name be set if you want it to be sent.
+12
source share

The name attribute is used when submitting the form, i.e. to create a name-value pair that will be processed on the server. The id attribute is used to determine the location and element in the DOM. Usually the name is used only for form elements.

Literature:

http://www.w3.org/TR/html401/interact/forms.html
http://www.w3schools.com/html/html_forms.asp

+4
source share

I usually use both. As you mentioned, name is useful for using data through JavaScript, as well as after sending it. Feel free to use extra characters in the name as needed: I prefer to use [] in my names when the input will be used on the server side.

The id attribute can be used to access an element through the JS / DOM. It is also used by the <label> for attribute. If you do this using checkboxes, for example, clicking on a shortcut will cause the window to be checked. This is a big plus for ease of use.

+1
source share

I find it good practice to have a name and id for each form element. The reason is that if you want to add shortcuts or style through tables (which you should do), then it makes sense to have both.

As for accessing it using javascript: the best way would be to go with the element id, because if you change the name of the form, everything will break. This does not happen if you use an identifier.

+1
source share

I prefer to use identifiers, because the β€œfunction” (that is, what you are trying to achieve) of your code is not related to semantics. For me, GETElementById ('myid') stands out more and is more readable, since just "myid" is scattered among the code. In addition, you can easily rename items. What is my 2p worth!

+1
source share