tags:

views:

17

answers:

1

I'm trying to change the background positioning for a label based on whether or not an adjacent checkbox is checked.

I figured out how to select adjacent fields with jQuery and I verified that this selector is indeed working:

$("input[type='checkbox'] + label")

But I can't figure out how to access the checkbox.

Here's what I have so far...

$("input[type='checkbox'] + label").click(function() {
    $(this).css("background-position", $("--adjacent checkbox here--").attr('checked') ? "bottom" : "top");
});
+1  A: 
$("input[type='checkbox'] + label").click(function() {
    var $th = $(this);
    $th.css("background-position", $th.prev().attr('checked') ? "bottom" : "top");
});

http://api.jquery.com/prev/

jQuery's prev() method selects the immediate previous sibling if one exists.

patrick dw
There is also next and siblings as well.
Mark
Awesome, thank you. I thought that `prev()` and `next()` only selected the previous and next elements that were satisfied by the selector. I didn't realize they could be used to grab any DOM element at all. But that definitely works.
Steve Wortham
@Steve - Glad it worked. Yeah, those (and others) are traversal methods that actually crawl the DOM for you from a starting point. Very handy. :o)
patrick dw
Now that I think about it, I understand completely why that works. The object passed through `this` holds a reference to the DOM object, and has no direct connection to the selector that was used to get that object. I should have thought of that.
Steve Wortham