Html forms

I’m currently learning html forms i found that we use both “name” attribute as well as “id”
What’s the difference between the name and id attributes?

It’s always good to check documentation for queries like this: HTML attribute reference - HTML: HyperText Markup Language | MDN

You’ll see that the id is a unique global identifier you give to an element. name specifically deals with references for elements inside forms and how the form interacts with them.

For example, if you had "myChoices" dropw-down, you might want to style that drop-down to be centered with css (or with javascript), you would use its id tag.

If upon pressing submit you wanted to access it you then use its name (maybe you have 2 different dropdowns so you need to make a distinction by name).

1 Like

To add to the above :point_up:

According to the MDN page on the <form> element, in reference to the name attribute:

The name of the form. Deprecated as of HTML 4 (use id instead). It must be unique among the forms in a document and not an empty string as of HTML5.

However, from what I have seen, this does not apply to elements such as <input>.

As an added note, you can obtain an element, and it’s values/properties, in JavaScript through it’s class, id, or name. However there can only be one element with each unique id. This means that all of the console.log()'s below log the same:

<!DOCTYPE html>
  <title> Example </title>

  <input type="text" name="text_field" class="text_field" id="text_field" value="letters">


  input = document.getElementsByName("text_field");
  input2 = document.getElementsByClassName("text_field");
  input3 = document.getElementById("text_field");



Over all the different options give you plenty of different tools to make working more flexible.

1 Like