1

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

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Anton Guryanov
  • 12,109
  • 1
  • 15
  • 16

2 Answers2

3

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?"

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
0

use tag label instead of JS

pure html here http://jsfiddle.net/RAkjk/

primetwig
  • 465
  • 3
  • 12
  • 1
    I do not own the website, so I can't change its html code (I could do this with Greasemonkey, but it is much more difficult then what I want to do) – Anton Guryanov Mar 19 '13 at 10:09