Is it correct to use the same id and name in the input of an html form?


I would like to know if it is a good practice to place the same in id and in name when I am going to program, for example, in HTML and PHP. Could it affect the code when it is already advanced? What consequences could it have to do?

asked by YomismoDJ 19.04.2017 в 02:28

2 answers


There is a difficulty when assigning the same name and id to an element. Internet Explorer browsers lower than version 10 can not distinguish between name and id when the getElementsByName() method is used.

Mozilla says it in his official documentation :


The getElementsByName method works differently in different   browsers In IE < 10, getElementsByName() method will also return   elements that have an id attribute with the specified value. So you   should be careful not to use the same string as both a name and an   ID .

 The getElementsByName method works differently   in different browsers. In IE
answered by 19.04.2017 / 04:02

id and name are different things but there is no problem with the same value.

id is to uniquely identify an element within the document. The ids should not be repeated and in case of repetition, the function getElementById returns the first of the elements. It is used mainly on the client's side to locate and modify a particular element.

name instead, it is usually used to identify the elements of a form: <input> , <textarea> and <select> when a form is sent to the server. Specifies the key of the clave/valor that is received on the server. In other words, the data is already associated with the name of the element and not with its id (which is unknown on the server side).

Basicmante <input name="nombre"> reaches the server in the form of ... $POST["nombre"] (if POST is used).

It should be noted that getElementsByName always returns an array even if it finds only one element.

Another important thing about name is that if several elements have the same name , depending on the element behaves differently:

If you have several <input type="submit"> with the same name, the server reaches the value of the pressed button and not the others, so that a button can be easily identified. Something similar happens with radio .

In conjunction with php , if you use a name like this: name="nombre[]" can be read directly as an array on server side like this: $nombre = $_POST['nombre']; (for example in a set of checkbox or text ).

answered by 19.04.2017 в 02:56