开发者

jquery checkbox attr change seems not to work

开发者 https://www.devze.com 2023-02-20 19:25 出处:网络
Does anyone have any idea why this code seems not to work? 开发者_如何学运维What am I doing wrong?

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>


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.


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

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


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.


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?

0

精彩评论

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

关注公众号