开发者

jQuery responds to click() differently for user and programmatic triggers

Here's the code:

this.Form.find("input[type=checkbox]").click(function(event) {
    if ($(this).is(":checked")) {
        console.log("checked");
    }
    else {
        console.log("unche开发者_JAVA百科cked");
    }
});

If the checkbox is not checked, and I click with the mouse, I get "checked". If I trigger it programmatically like $("#someCheckbox").click(), I get "unchecked". How to make the two behave the same way?


After seeing your comment, I did a little bit of testing. I was able to get it to work the way you want in FF and IE using the DOM click method on the checkbox instead of triggering the jQuery click event.

<script type="text/javascript">
$(function() {
    $("input:checkbox").click( function() {
        if ($(this).is(':checked')) {
            alert('checked');
        }
        else {
            alert('not checked');
        }
    });
    $('a').click( function() {
        $('#cb').get(0).click();
        return false;
    });
});
</script>


<p>
<a href='#'>click a box</a>
</p>
<input id="cb" name="cb" type="checkbox" value="0" /> 0<br />


This issue comes from a rather thorny event handling timing issue deep in the bowels of jQuery. Here's a blog post discussing it in some detail (plus a link to the SO answer I got that post from).

Luckily, if what you are trying to do is programatically toggle a checkbox and trigger that checkbox's bound functions, 9 times out of 10 you can sidestep all of that complication by simply swapping your .click(function(){}) binding for a .change(function(){}) binding.

Unlike click, with change the bound event will always by definition fire after the click has caused the checkbox state to change. The function will always see the new checkbox state.

Like click, the event only fires after a click-like event hits the checkbox, so when manipulating the checkbox with js you will still have the choice of silently changing the click state with .attr() and .removeAttr() without triggering the bound functions, or .click()ing the checkbox to trigger the bound functions.


When you're clicking the checkbox you're changing its state from unchecked to checked or vice--versa. When firing the click event, you're just calling the handler function with a false event object, you don't actually change the state.

Before firing your event, toggle the checkbox state by adding the following code:

var myInput = $("input[type=checkbox]")[0];
myInput.checked = !myInput.checked;

You might have to substitute the selector to work with your own code.


You might want to check out that it works both in Firefox and Internet Explorer. I ran into some issues with the check box. Check it out here!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜