用于处理具有复选框组的ID的语义上适当的方式

时间:2018-02-05 21:10:13

标签: html label html-form semantic-markup

我正在制作一个冗长的表单,其中包含用户可以检查多个答案的问题。基本代码如下(我使用语义UI进行基本样式化):

<form class="ui form new-form" action="#" method="get">
    <div class="ui form">
        <label>What fruits do you like?</label>
        <div class="field">
            <div class="ui checkbox">
                <input type="checkbox" tabindex="0" name="fruits" value="apples">
                <label>apples</label>
            </div>
        </div>
        <div class="field">
            <div class="ui checkbox">
                <input type="checkbox" tabindex="0" name="fruits" value="bananas">
                <label>bananas</label>
            </div>
        </div>
        <div class="field">
            <div class="ui checkbox">
                <input type="checkbox" tabindex="0" name="fruits" value="dylan-carty">
                <label>pears</label>
            </div>
        </div>
    </div>
</form>

我想使用for / id for accessibility reasons来应用我的标签。

在这种情况下,顶部标签(&#34;您喜欢什么水果?&#34;)指的是整套复选框。如果这是一个选择/选项集,我知道您将ID应用于包含<select>标记。我看到有三种可能的解决方案。

  1. 将所有复选框放在<div>中,并在&#34中为其提供与for值相同的ID;您喜欢哪些水果?&#34;标签。为每个复选框标签指定一个与其输入匹配的ID。这为Semantic UI留下了复选框的现有样式,但我不知道它是否是语义。
  2. 将所有复选框放在<fieldset>标记中,并在&#34中为其提供与for值相同的ID;您喜欢哪些水果?&#34;标签。为每个复选框标签指定一个与其输入匹配的ID。这对我来说似乎更具语义性,但由于语义UI为<fieldset>提供了一种风格,因此我需要覆盖该风格。
  3. 包裹&#34;你喜欢什么水果?&#34;标签围绕整个复选框,如方法1 here
  4. 所示

    研究:

    • 搜索包含&#34;多个复选框&#34;的问题,但大多数处理的情况是每个复选框都不同,不是较大的组的一部分,或者如何选择它们
    • 一般搜索&#34;最佳做法复选框组ID&#34;并确实提出了this,建议在<legend>内加<fieldset>。但是,我不希望将<label>用于我的所有其他输入,并仅针对复选框组切换为<legend>标记。

    是否有普遍接受的&#34;最佳做法&#34;在这种情况下?

    JSFiddle here

1 个答案:

答案 0 :(得分:1)

从语义角度来看,您的研究已经给出了答案。

使用fieldsetlegend

当谈到语义时,忽略默认样式,无论是原生HTML还是您正在使用的任何CSS框架。

fieldsetlegend标记专为此目的而设计。如果你想要迂腐,理论上,表格的全部内容也应该包含在fieldset标签中,并带有legend,因为你是&#34;超集&#34;的领域。

对您的HTML进行微小更改,您需要以下内容:

&#13;
&#13;
<form class="ui form new-form" action="#" method="get">
  <div class="ui form">
    <fieldset>
      <legend>What fruits do you like?</legend>
      <div class="field">
        <div class="ui checkbox">
          <input type="checkbox" tabindex="0" name="fruits" value="apples" id="fruit_apples">
          <label for="fruit_apples">apples</label>
        </div>
      </div>
      <div class="field">
        <div class="ui checkbox">
          <input type="checkbox" tabindex="0" name="fruits" value="bananas" id="fruit_bananas">
          <label for="fruit_bananas">bananas</label>
        </div>
      </div>
      <div class="field">
        <div class="ui checkbox">
          <input type="checkbox" tabindex="0" name="fruits" value="dylan-carty" id="fruit_pears">
          <label for="fruit_pears">pears</label>
        </div>
      </div>
    </fieldset>
  </div>
</form>
&#13;
&#13;
&#13;

现在你需要将CSS调整为适合你的东西。

现在是棘手的部分。 Web开发和编程通常是一种平衡行为。知道什么是最佳实践&#34;很好,但知道这些是指导方针而不是规则也很重要。您可以自行决定保留哪些内容以及忽略这些指导原则,以确保您的工作可维护和可交付。

我该怎么办?根据提供的信息,使用fieldsetlegend