3

When setup like this, clicking on a label that has a child button triggers button's onclick event:

function fireButton() {
  console.log("Button fired!");
}
<label>Label
  <button onclick="fireButton()">Button</button>
</label>

is there a way to prevent this?

2
  • 2
    That is just a pattern you should avoid to begin with; common accessibility guidelines explicitly advise against nesting such interactive elements which have their own functionality into labels.
    – CBroe
    Nov 12, 2020 at 11:57
  • 1
    granted.. I'll work on a better design in the future. Nov 12, 2020 at 12:21

5 Answers 5

3

Add for attribute to label.

function fireButton() {
  console.log("Button fired!");
}
<label for=''>Label
  <button onclick="fireButton()">Button</button>
</label>

3
  • For attribute associate with Id of its descendant. if you don't want want to associate it then set it blank. Nov 12, 2020 at 12:01
  • 1
    This did it for me! Simple and effective use of builtin functionality, even if my design is poor and deserves refactoring as stated by @CBroe in the comments stackoverflow.com/questions/64803356/… Nov 12, 2020 at 12:20
  • You design it well to elaborate the issue. :-) Nov 12, 2020 at 12:26
2

You can put the button outside the label

<label>Label</label>
<button onclick="fireButton()">Button</button>
2

You can add preventDefault for labels and keep the existing code:

document.querySelector("label").addEventListener("click", function(event) { 
    event.preventDefault();
}, false);
1

You could use a different tag e.g <span> rather than the label But if you really need to use the <label>, you should prevent the default behaviour of the label onclick() like so:

function fireButton(){
//add actions here
}

function preventDefault(event){
  event.preventDefault()
}
<label onclick="preventDefault(event)">Label
  <button onclick="fireButton()">Button</button>
</label>

2
  • I could add that line in the body of fireButton() if I passed the event on too, right? Nov 12, 2020 at 12:17
  • No, Adding it to the fireButton() won't be affecting the behaviour of the label. Which means that the button click will still be triggered when you click the label. So it has to be on the label's click event @GugaFigueiredo
    – ibrahim s
    Nov 12, 2020 at 12:41
1

Here's an approach in CSS which also disables triggering button's :active state when clicking on label. Overriding label's onClick event does not do that.

label {
  pointer-events: none;
}
    
button {
  pointer-events: initial;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.