I have a list of possible products a user can buy. For doing it, I use ul tag combined with li. Every element has a checkbox that allows the user to choose if select the product or not.

Some products have related information. In order to describe this, I would like to store the data inside an hidden input. But because the selection and the information are related to a product I thought to use a label that contains the checkbox and the hidden input.

Something like

<label class="product">
  <input class="product-checkbox" name="product1" type="checkbox">
  <input type="hidden" name="product1-information" value="{...}" />
  <span class="product-name">Product1</span>
</label>

If I understood correctly, a label cannot refer to an hidden input but in the above example, accordingly to the w3c, the labeled control is the checkbox.

Anyway I'm wandering if a label can contains checkbox and an hidden input.

So, is the above snipper correct?

推荐答案

You're right on both counts. From MDN

The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:

<label for="username">Enter your username:</label>
<input id="username">
<label for="username">Forgot your username?</label>

Elements that can be associated with a <label> element include <button>, <input> (except for type="hidden"), <meter>, <output>, <progress>, <select> and <textarea>.

(emphasis mine)

That makes it pretty clear to me that (a) multiple things inside a <label> block is entirely acceptable, and (b) hidden inputs will not be considered targets of the label.

Html相关问答推荐

使用 fontawesome 的图标后,它改变了我的字体系列

单个表格行中不同项目的不同对齐方式

使用 TS 将
  • 项目附加到
  • 如何在react 应用程序中从服务器响应创建 childElement

    绝对锚标签与具有绝对跨度的锚标签

    如何随着material 徽章的索引增加而更改 colored颜色 ,例如(0,1,2,3,..etc)在Angular

    如何增加 标签按钮的可点击区域?

    如何更改 bootstrap 程序中表单控件弹出窗口中必填字段的默认消息?

    我可以使用哪些 HTML5 标签而不用担心浏览器的兼容性?

    使外部 div 自动与其浮动内容高度相同

    textarea 下的额外空间,因浏览器而异

    在绝对定位的 Div 上居中对齐

    正文高度 100% 显示垂直滚动条

    如何在 JavaScript 中获取文本框的值

    如何将 Base64 字符串转换为 javascript 文件对象,如文件输入表单?

    如何在 HTML 文本下添加虚线下划线

    CSS colored颜色 与背景 colored颜色 与背景?

    td宽度,不工作?

    隐藏 iframe 上的水平滚动条?

    我可以从 javascript 中将字段标记为无效吗?