arekstasiewicz
arekstasiewicz

Reputation: 383

jquery checkbox attr change seems not to work

Does anyone have any idea why this code seems not to work? What am I doing wrong?

JQuery 1.5.1 is used.

JS code:

$('#search_filters #discipline a').click(function(){

    var checkbox = $(this).next(':checkbox');

    if (checkbox.attr('checked')) {
        checkbox.attr("checked", true);
    } else {
        checkbox.attr("checked", false);
    }

    $(this).children('img').toggleClass("active");

    return false;
});

HTML:

<li>
    <a href="#">
        <img class="inactive" alt="Football" src="/images/disciplines/e9bc7681813110c/thumb.png">
    </a>
    <input type="checkbox" name="search_discipline[7]" value="1" class="search_discipline">
</li>

Upvotes: 1

Views: 3570

Answers (4)

Aaron Lampros
Aaron Lampros

Reputation: 290

I just ran into this myself. It seems in jQuery 1.5.1 and 1.5.2 setting the checked attribute is a bit buggy. I had better luck with $(':checkbox').val(boolean) (which is even a bit easier).

Update: after some digging, it seems the webkit inspector doesn't actually show the checked attribute in the DOM, but jQuery reads/writes it properly. Very odd. Serves me right for using the nightly webkit builds for dev.

Upvotes: 1

Reporter
Reporter

Reputation: 3948

Just two helpful ideas to check the change for attributes:

  • Write the plain HTML first, without Javascript. Did it work? If so, then write it with JS
  • If you had modified an html tag recall the attribute itself, so you can check that your code had been executed well. E. g. alert($({your target object}).attr({the attribute which added}));

That's what I do in the most cases.

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30500

Some pointers:

  1. $('#search_filters #discipline a') will be selecting all a elements that descend from #discipline that descend from #search_filters. Is this what you indend?

  2. Are you remembering that .next() returns a sibling.

  3. What happens if you remove the href='#'?

  4. Does your click event even fire?

Upvotes: 0

Alex
Alex

Reputation: 7374

The value of a "checked" attribute should be "checked":

if (checkbox.is(':checked'))
{
    checkbox.attr("checked", "checked");
} else {
    checkbox.removeAttr("checked");
}

Upvotes: 1

Related Questions