tags:

views:

38

answers:

3

Here's the code:

this.Form.find("input[type=checkbox]").click(function(event) {
    if ($(this).is(":checked")) {
        console.log("checked");
    }
    else {
        console.log("unchecked");
    }
});

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?

+2  A: 

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 />
tvanfosson
+1. The click event is not the same as the value change event.
jvenema
This sets it to unchecked, actually.The outcome of either method (mouse or code trigger) is the same. The checkbox changes state, no problem there. It's the order of things that is the problem. Let's say there's a break at the line with the if statement in my code. Triggered with mouse, the element will be in checked state at breakpoint, but in an unchecked state if I trigger programmatically. If I continue, the end state is the same either way. That's what confusing me.
Moss
@Moss -- I see what you mean now. I was able to get it to work using the DOM click event rather than jQuery. I've updated.
tvanfosson
A: 

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.

Andy E
A: 

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!

Gutzofter