Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does a Label Inside an Input Trigger a Click Event

Tags:

html

jquery

If I have an input inside a label, why does every word in the sentence trigger a click event?

Here is a jsFiddle for an example. No matter what word you click on in the first sentence, the event is fired.

I added some CSS on the input so you can see that no matter where in the first label you mouse over, it's like you are hovering over the input. I also added a second label using an a tag inside the label which works as I would expect the input to work (the click event does not fire when you click on a word in the label).

<label>Click <input type="submit" value="here" /> to go somewhere.</label>
<label>Click <a href="#">here</a> to go somewhere else.</label>

$('input, a').click(function() {
    alert('Clicked');
});

My two questions are:

  1. Is there a way to use an input inside a label in a way that the label does not trigger the click event?
  2. In my example, why does the click event fire on every word in the sentence?
like image 828
Brian Avatar asked Oct 08 '13 13:10

Brian


1 Answers

This is part of the HTML spec - label elements increase the hit area of the related input. You can handle the click yourself and preventDefault(), however it will not stop the button UI changing on click.

$('input, a').click(function() {
    alert('Clicked');
});

$('label').click(function(e) {
    e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Click <input type="submit" value="here" /> to go somewhere.</label>
<label>Click <a href="#">here</a> to go somewhere else.</label>

Alternatively you could change the label elements to span with the appropriate styling to make them behave the same way, although you will be hurting your users' experience.

like image 110
Rory McCrossan Avatar answered Sep 20 '22 20:09

Rory McCrossan