0

My understanding of this is that if you use the id for an input it is linking to the "for" attribute for the corresponding label. However, I am unsure how it works in the reverse circumstance.

My understanding of the name attribute was to send that name to the server, but in the case where you are making a checkbox the value attribute is performing this task. Am I overcomplicating a simple concept here?

  • 1
    Yes you are overcomplicating a simple concept :). IDs uniquely identify an element in the DOM. That's all they do. The `for` attribute uses that fact to allow linking a `label` to a form element semantically. It says, "this is the label for that element". And that's it. – Heretic Monkey May 28 '19 at 16:14
  • The `name` attribute is actually used on a checkbox to send the appropriate value to the server. If you do not provide one, the value won't get sent. – Heretic Monkey May 28 '19 at 16:16
  • @HereticMoney Thank you that does clear it up. What task is the value attribute performing when using an input? –  May 28 '19 at 16:18
  • It provides the value. Basically, when sending data from the form to the server, HTML has to give the server the name of the element and its value. Back in the beginning, this was done through the URL using query strings; the `?isChecked=true` stuff. The name of the element was used for the `isChecked`, and the `true` was the value. – Heretic Monkey May 28 '19 at 16:20
  • @HereticMonkey Thank you. –  May 28 '19 at 16:23
  • Sure. See also [MDN's article on how data are sent with HTML forms](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data) – Heretic Monkey May 28 '19 at 16:24

1 Answers1

0

The label has 2 main functions: identify to the HTML what the label is for, and in most common browsers clicking the label will set the focus to the input. Below are the possible scenarios. Keep in mind it's usually easiest to set both the id and name of the input to the same value.

Will not link label to input:

<label for="myInput">My Input</label>
<input name="myInput">

Will not send form data to server (custom-built AJAX objects that include by id are an exception):

<label for="myInput">My Input</label>
<input id="myInput">

Also will not link label to input (for needs to be id, not name):

<label for="input">My Input</label>
<input name="input" id="myInput">

Correct:

<label for="myInput">My Input</label>
<input name="myInput" id="myInput">

Also correct with non-matching name/id:

<label for="myInput">My Input</label>
<input name="input" id="myInput">
MaKR
  • 1,822
  • 1
  • 16
  • 29