views:

106

answers:

2

Hi all, ok quick scenario:

html:

<span class="answer">blah<input type="radio" value="1"></span>

jquery:

$("span.answer").click(
function() {
check = $("input", this);
check.attr('checked', check.attr('checked') === true ? false : true);
);

Ok so this will check/uncheck the child radio input inside the selected span when I click inside it.

The problem I have is that I don't want to run this event when I actually click on the radio button itself (obviously because jquery will see the radio button as checked and uncheck - in effect the exact opposite of what should happen usually). Something along the lines of this:

$("span.answer:not(span input)").click

This of course doesn't work. Any ideas? Thanks in advance!

Leo

+4  A: 
Gaby
Yep this method will work (without javascript) but doesn't play ball in ie6.
Leo
wasn't aware of this .. you can use the `for` attribute to make this work.. look at updated answer..
Gaby
Yes that certainly works thank you. I didn't want to use ids for these particular radio inputs but I guess I can work it differently. Any ideas about the broader jquery selector problem detailed below?
Leo
@Leo, You should use the code of Koobz for that, but for a more generic approach you could change it to `$('.answer').click( function(){/*your normal code here*/} ).children().click( function(evt){evt.stopPropagation();})`. This might become overkill, though, in situations where your `.answer` element has lots of children (*1st level*)
Gaby
Great! Thanks for the very quick replies (and to Koobz et al).
Leo
+4  A: 
$("span.answer input").click(function(evt)
{
    evt.stopPropagation();
});

Will prevent the click event from bubbling up (and triggering the handler on "span.answer".)

Koobz
Yeah this definitely works as I need it to. Is this the most elegant solution to the problem do you think? There are many occasions where I have an event bound to element which I don't want to trigger when I click on a child of that element. I thought there might be some fancy selector technique to accomplish this along the lines of the example in my question.
Leo
This is the correct answer to the original question, however, using the <label for...> tag is the correct way to do it.
Blair McMillan
Yes, in this case, correct use of the `label` tag automatically results in the behavior you're looking for without javascript. Otherwise, there's no selector to accomplish what you're looking for. If you click on a child element, it bubbles up. It's the way thing work and it's usually desirable.
Koobz