Leo
Leo

Reputation: 105

How can I prevent jquery from selecting a parent when I click on one of the children in that parent?

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

Upvotes: 2

Views: 232

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

There is a specific html tag to accomplish what you try to do with jquery and javascript ..
it is the label tag

<label>blah<input type="radio" value="1" /></label>

this will have the effect you want

[update] For Internet Explorer 6 to play nice use the complete syntax of the label by using the for attribute which targets the id of an form input/select/etc.. element..

<label for="radio_1">blah<input id="radio_1" type="radio" value="1" /></label>

Upvotes: 4

Koobz
Koobz

Reputation: 6938

$("span.answer input").click(function(evt)
{
    evt.stopPropagation();
});

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

Upvotes: 5

Related Questions