I have a label
with "for="the pointer to the checkbox input"
" and as long as I know, this for
can be added only for label
. Therefore, I need to add inside of the label
a <button>
(I need it), but the click event isn't working properly - it doesn't check the checkbox the for
is pointing to.
What are the possibilities I can use here if I must place <button>
inside the label
, with only html+css coding?
some code for example:
<input type="checkbox" id="thecheckbox" name="thecheckbox">
<div for="thecheckbox"><button type="button">Click Me</button></div>
You can use transparent pseudo element that overlays the checkbox and the button itself that will catch mouse events.
Here's an example:
html:
css:
It turns out you can make a
<button>
operate an input, but only if you put the<label>
inside the<button>
.Although this contravenes the W3C specs:
HTML:
JS:
Target is the click target, currentTarget is the label in this case.
Without the if statement the event is fired twice if clicked outside of the event preventing area.
Not cross browser tested.
The best solution is to style is like a button.
If you're using a CSS framework, like bootstrap, you can give the label classes such as btn and btn-default. This will style it like a button. You may need to adjust the css property of the line-height manually like so:
Then, to get the on click styles as a button, add these styles:
This will take the input that is checked and give the next label element in the dom that has the class btn, bootstrap btn-default button clicked styles. Adjust colors as fit.