Why do we need the value attribute for checkbox inputs?

The following code is from this exercise

label for="lettuce">Lettuce</label>
<input id="lettuce" type="checkbox" name="topping" value="lettuce">

Is the value attribute necessary here?

The value attribute on the checkbox is used when the form is interacting with a server. So when you set the value as lettuce, that means when the form is submitted and that box is checked, the value it sends back to the server is topping=lettuce. This can then be set up on the server side to be interpreted and added to the order. If you don’t give it a value then it’ll just send an “on” or “off” value, which might be okay but isn’t particularly clear. You can read the MDN documentation for more information.

1 Like

What if we simply use the name as “lettuce”? Why are we using the same name - topping - for every item with a checkbox? The exercise says that it groups the inputs together, but why would we need to do that when we have checkbox inputs (and not radio inputs) where we can select multiple items? Wouldn’t it be a problem if we have multiple name-value pairs with the same name sent to the server?

So firstly, if you have multiple checkboxes with the same name, the way it is sent it by combining them into a single string, so for example if you had the below:

<input id="lettuce" type="checkbox" name="topping" value="lettuce">
<input id="pepperoni" type="checkbox" name="topping" value="pepperoni">
<input id="tomatoes" type="checkbox" name="topping" value="tomatoes">

And lettuce and pepperoni were checked, the string that would be sent would be “topping=lettuce&topping=pepperoni”. So the idea is that you would have something on your backend (using regex most likely) to parse this string into say, a list or just a more readable format. The idea is that you could have many checkboxes per page, and so the idea is the relevant ones are grouped together. You could also use a different name for each checkbox, but then you are parsing, in the above case, 3 different inputs instead of a single one with all the info you need.

So the short answer is; no, it wouldn’t cause a problem if there are multiple checkboxes with the same name value, and in fact it is designed around this idea of having multiple checkboxes selected for the same thing.

Also important to bear in mind that the input tag was added to HTML in the 90’s, specifically 95 I believe. We didn’t have all of the server-side frameworks and tools back then that we have now, and so a lot of the production had to be done through sending minimal data due to low connections. Therefore a lot of data was sent using raw strings rather than using things like arrays and dataframes and such to send data. So there’s probably better ways such info could be sent now, however HTML is backwards compatible as much as possible, and so forms and inputs have been left largely unchanged in 25 years.

1 Like