javascript name vs ID

2019-02-17 03:31发布

问题:

As far as I know there are two ways to get the value from a textbox either

document.formName.textboxName.value;

or

document.getElementbyId('textboxId').value;

As I understand using form name would mean I have less code to write, as name can be used for posting data and getting the value (apart from using ajax). As where if I was just posting using a standard form I would use name to post but I cannot use id ?

e.g. in php I would use

$_POST['texboxName']; 

If I where to have and ID on the textbox I cannot get the value using php ?

Which is the standard recommened way of doing this, and is using name browser friendly? Links if possible please, thanks.

回答1:

The ultimate guide in this is the HTML specification.

Things that stand out there:

  • id is valid for any HTML element, while name only applies to a select few (a, input, textarea and maybe a few others).
  • An input (and textarea) element requires the name to be set if you want it to be submitted.


回答2:

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

References:

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



回答3:

I typically use both. As you mentioned, name is useful for using the data via JavaScript and also once it has been submitted. Feel free to use additional characters in the name as needed: I tend to use []s in my names when the input will be used in an array server-side.

The id attribute can be used for accessing the element via JS/the DOM. It is also used by <label>'s for attribute. If you do this with checkboxes, for example, clicking on the label will cause the box to become checked. That's a big plus for usability.



回答4:

I consider it good practice to have a name and id for each form element. The reason being that if you want to add labels, or styling via sytlesheets (which you should be doing), then it makes sense to have both.

As for accessing it with javascript: the better way would be to go with the element's id, becuase if you change the name of the form everything breaks. This does not happen when you use the id.



回答5:

I prefer using IDs, as the "function" (i.e.: what you're trying to achieve) of your code isn't tied up with in the semantics. For me, .GetElementById('myid') stands out more, and is more readable that just having "myid" scattered among the code. Plus you can more easily rename elements. That's my 2p worth!