Skip to content

svelte(a11y-label-has-associated-control) shows incorrectly when using if-statements #6442

@MarcusOtter

Description

@MarcusOtter

Describe the bug
The warning A11y: A form label must be associated with a control. shows up even if the label has an associated input inside it, when if-statements are used. Example:

<!-- A11y: A form label must be associated with a control. -->
<label>
    {#if true}
        <input type="text">
    {/if}
</label>

<!-- No warning -->
<label>
    <input type="text">
</label>

To Reproduce
https://svelte.dev/repl/ab0b74aea51c44f382d2378257406a66?version=3.38.3

Expected behavior
No warning as long as every branch is guaranteed to have a form control.

This also goes for more complicated statements like:

<label>
    {#if condition1}
        <input type="text">
    {:else if condition2}
        <textarea></textarea>
    {:else}
        <select></select>
    {/if}
</label>

Information about your Svelte project:
npmPackages:
rollup: ^2.3.4 => 2.46.0
svelte: ^3.0.0 => 3.38.1

Severity
Given the first workaround (below), not very severe. Minor inconvience. If I couldn't disable the warning it would've been near unbearable to code with it since the warning is on every single line of the label element (which wraps everything).

That being said, when ignoring the warning it does open up to actually making mistakes by having some branch of the if-statement not including a form control.

Workarounds

  1. Ignore it with a comment

    <!-- svelte-ignore a11y-label-has-associated-control -->
    <label>
        {#if true}
            <input type="text">
        {/if}
    </label>
  2. If you only have one control (or all of them share the same id)

    <label for="myControl">
        {#if true}
            <input type="text" id="myControl">
        {/if}
    </label>

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcompilerChanges relating to the compiler

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions