Holly
Holly

Reputation: 353

Is the "id" in an input tag necessary?

<p>
  <input type="text" id="search" name="keywords" />
  <input type="submit" value="Search" name="Submit" />
</p>

For the above code I was getting validation errors, but once I removed the id="search" the validation was good and error-free. I thought you needed an id, but I'm wondering if it is supposed to be there?

Upvotes: 7

Views: 23770

Answers (4)

Gabriel Petersen
Gabriel Petersen

Reputation: 53

For inputs that the user has access to, it is an accessibility requirement that the inputs have an associated label to give an informative description of what the input does. Thus, it is a requirement that these inputs have IDs that are unique across the page.

See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#accessibility_concerns

Upvotes: -1

Nathan
Nathan

Reputation: 1

Daniel is correct. A label's for attribute is associated with an input's name attribute. In this way, if you select a label with for="first_name", it will select the input with name="first_name".

Upvotes: -4

Paolo Bergantino
Paolo Bergantino

Reputation: 488394

Do you have any other elements with that id in the document? That would be the only reason for validation to fail. IDs are meant to be unique in the document, if you have it elsewhere it would be invalid.

IDs are good when you plan on doing some sort of client-side work on the element, as an element that has an ID can easily and quickly be retrieved by Javascript. It is also good when you are using <label> elements, as you can then use the for attribute (which takes an ID) to point to the field.

Other than that, it doesn't really matter.

Upvotes: 13

Daniel A. White
Daniel A. White

Reputation: 190935

You do not need the ID attribute. The name attribute is the one that gets passed.

Upvotes: 5

Related Questions