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:
input
inside a label
in a way that the label
does not trigger the click event?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With