Consider following snippet:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<form>
<a id="a" href="http://google.com">Goooooogle</a>
</form>
<script>
$(function() {
var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
e.stopPropagation();
// do something useful
});
});
</script>
</body>
</html>
I want to get a checkbox inside <a>
, and get following on-click behavior:
- Toggle check mark normally as usual
- Do something useful like AJAX-request
- Stay on this page, i.e. not be redirected to an
a href
Also I want to not override default behavior if I click anywhere in a
, but not on checkbox. I.e. I want to allow to execute all event handlers associated with a
click itself.
I thought that should be pretty easy, but I can't get desired behavior. Either:
- I get redirected to Google if I put a code provided.
- I don't get check mark toggled if I use
e.preventDefault()
ofreturn false;
. Furthermore in that case checkbox ignores explicitcheckbox.attr('checked', 'checked')
and all other possible ways to set the check mark.
Where is the catch?
UPD: This works as expected in Chrome, e.g. I'm not redirected on click, but fails in Firefox. Is there cross-browser way?
I Know this question is over 5 years old, but I had the same issue recently and the work-around I found was to add an onclick function to the checkbox and in that function call event.stopImmediatePropagation().
from w3schools: "The stopImmediatePropagation() method prevents other listeners of the same event from being called"
ie...the anchor.
here's a modified script
i unbind the click event on the
<a>
and rebind it with a event to check/uncheck the checkbox and also prevent the default.I know this is an old question but some may still be curious since it was never really fully answered without a messy hack or workaround. All you have to do is simply check where the event's target originated.
So using your example (jsfiddle):
Well, it looks like a known Firefox bug, which leads to following link on checkbox click regardless of handlers' code. As a bit dirty workaround one can use: