Checkbox inside anchor click behavior

Consider the 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 check the box inside <a>and get the following behavior when clicked:

  • Toggle the checkbox normally as usual
  • Do something useful like an AJAX request
  • Stay on this page, i.e. do not redirect to a href

Also, I want not to override the default behavior if I click anywhere abut not on the checkbox. That is, I want to allow the execution of all event handlers associated with a amouse click.

I thought this should be pretty easy, but I can't get the behavior I want. Or:

  • I will go to Google if I put the code.
  • , e.preventDefault() of return false;. , checkbox.attr('checked', 'checked') .

?

UPD: Chrome, . , Firefox. - ?

+5
4

, Firefox, checkbox, . :

var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
    setTimeout(function() { checkbox.prop('checked', !checkbox.prop('checked')); }, 10);       
    // do something useful on clicking checkbox and but not surrounding link
    return false;
});
+4

, , , . , , , .

, (jsfiddle):

// Don't change pages if the user is just changing the checkbox
$("#a").click(function(e) {
    //e.preventDefault(); // Optional if you want to to keep the link from working normally

    alert("Click came from: " + e.target.tagName);
    if (e.target.tagName != "INPUT") {
        // do link
        alert("Doing link functionality");
    } else {
        // do something useful
        alert("Doing checkbox functionality");
    }
});
+3

, 5 , , , , , onclick event.stopImmediatePropagation().

w3schools: " stopImmediatePropagation() "

..... .

function checkbox_onclick(event){
event.stopImmediatePropagation(); 
}
+1

script

var checkbox = $('<input type="checkbox"></input>');
var a = $('#a');
a.unbind("click").click(function(e) {
    e.preventDefault();
    checkbox.attr('checked', !checkbox.attr('checked'));
});
checkbox.prependTo(a);
checkbox.click(function(e) {
    e.stopPropagation();
    // do something useful 
});

i click <a> , / , .

0

All Articles