The Greasemonkey script stops ticking the boxes after a few clicks?

advertisements

I use a website, which has lots of checkboxes to enable/disable different options. But there is a disadvantage: to check the checkbox, you need to click on the checkbox, but I want to be able to click the label, because it is easier. So I decided to write a Greasemonkey script to add this functionality

$("div.option").click(function() {
    $checkbox = $(this).children("input");
    isChecked = $checkbox.is(":checked");
    $checkbox.attr("checked", !isChecked);
});

I enabled this script and then I visit the webpage. First I click on the option, and the checkbox checks! Then I click again, and it unchecks. But further clicks do not do anything. And this goes for all options on the webpage, it works for first two clicks, but then stops working. How to fix the script to make it work permanently?

I use Firefox 19.0.2 on Ubuntu 12.10


You can't just toggle the value of the checked attribute like that. The attribute is not the same as the checked property / state.

The correct way to do this in jQuery is to use .prop(), like so:

$("div.option").click ( function () {
    var $checkbox = $(this).children ("input");
    var isChecked = $checkbox.is (":checked");
    $checkbox.prop ("checked", !isChecked);
} );

See "How do I check a checkbox with jQuery or JavaScript?"