uionut351j
uionut351j

Reputation: 37

label inside of button - click button and activate the label

When you click on this button, it will only checkoff the checkbox if you click on the "Hello" text. If you click on the button but not the text, it will not check off the box. How can I make it so no matter where I click on the button, it will check off the box?

<button>
    <label for="myId">Hello</label>
</button>


<input id="myId" type="checkbox" />

Upvotes: 0

Views: 1474

Answers (3)

tyrrr
tyrrr

Reputation: 538

If label is not the only element in the button, one can still follow Firman's great suggestion (extend your label to fill the parent element) without affecting internal layout by using pseudoelements (::before/::after).

If desireable, button's border can be included using negative inset value.

button {
  padding: 1em 4em;
  position: relative;
}

label::after {
  content: '';
  position: absolute;
  inset: 0;
}
<button>
    <label for="myId">Hello</label>
</button>

<input id="myId" type="checkbox" />

Upvotes: 0

codelover1
codelover1

Reputation: 171

Had the same problem: I even tried to make the label fill the button fully but it doesn't work. So what you can do is create the label, using JavaScript, in handleClick, assign its for attribute, click it, and remove it:

const handleClick = (e: MouseEvent<HTMLElement>) => {
  const label = document.createElement("label")
  label.htmlFor = props.fieldName
  document.body.appendChild(label)
  label.click();
  label.remove();
}

In this case you don't even need to put your label inside button:

<Button onClick={handleClick}>Upload an Image</Button>

Upvotes: 1

Firman Putra
Firman Putra

Reputation: 142

You need to make the label to be full width and height as of the button like so:

<button style="padding: 0;">
    <label style="display: block; padding: 20px;" for="myId">Hello</label>
</button>


<input id="myId" type="checkbox" />

Here is the fiddle: https://jsfiddle.net/hxoqrf7v/

Upvotes: 1

Related Questions