Mihir Patel
Mihir Patel

Reputation: 2372

Can you wrap form elements such as <label> and <input> in HTML <button> tag?

I am building a component that requires to hide input by adding a css property of opacity to 0. But the look and feel of this component is a button. The reason to hide input is for selection purpose. Input element supports radio type.

Question1: What are the implications of wrapping a button around the form elements? Is there any accessibility issue? Question2: Instead of a <button> tag, is it better to use perhaps a <fieldset>?

Below is the Vue template for the component?

<template>
    <button :class="[$style['button-group-item'], sizeClass, classObject, variationClass]">
        <label class='button-group-item__label'>
            <input class="button-group-item__input" type="radio" :checked="checked" @change="$emit('change', $event.target.checked)"/>
            <span>
                {{ text }}
            </span>
        </label>
    </button>
</template>

Upvotes: 1

Views: 860

Answers (2)

Neha Sharma
Neha Sharma

Reputation: 772

Yes, there will be accessibility issues.

1) Using Button will confuse the voice over software. The focus states will also behave incorrectly (keyboard focus).

2) At the code level, you need to prevent the default behavior of Button.

3) You are Breaking the rules of the semantic tag of the HTML5

4) Do not use Button if you are not doing any action. Make the fieldset from CSS look like a button.

Upvotes: 1

QuentinC
QuentinC

Reputation: 14862

You shouldn't wrap your input+label in a button. The result is going to be weird:

  1. There shouldn't be any focusable element (such as input) inside another focusable element (such as button).
  2. What the accessible label of the button should be ? It's probably going to be confusing.
  3. What's going to be happen when you click on the button ? It's going to be unclear because the accessible name is going to be unclear, too.
  4. Should the button be activated when clicking on the input, since the input is inside the button ? The answer depends on the browser and whatever it is, it's going to confuse / don't do what's expected and frustrate users.

For all these reasons, I heavily discourage you from using a button. Using a fieldset is much better, it's the normal way to go here. Use CSS to make your fieldset look like a button.

Upvotes: 4

Related Questions