views:

24

answers:

2

I have a container element say

<div id="myContainer">
  <form action="" method="post">
   Radio: <input type="radio" name="myRadio" id="myRadio" value="1" />
  </form>
</div>

So if I assign a click event to the $('#myContainer') and also a click event to $('#myRadio') is there a way to get them both to fire? Currently, because there is a click event "above" the form element, which has a return false to stop the page jumping, I cannot click the radio button.

Is there a way to tackle this? Or do I need to be more specific in my selectors? Or even $('#myContainer:not("#myRadio")') ? (is that even valid?)

A: 

To stop the page jumping use event.preventDefault() instead of return false; which is currently stopping the event dead in its tracks.

The natural behavior is for the event to bubble, so all you need to do to get both handlers firing is not interfering with the bubble via return false :)

Nick Craver
Ah, this makes sense. Will it make a difference if the form I'm using is being injected using javascript? As it will appear after the dom is finished loading, so I'd need to act on it again after dom load.
DavidYell
@DavidYell - If you need to attach event (`click`) handlers dynamically then you need to use `.live()` or `.delegate()`, but the bubbling itself won't be affected by when they were added.
Nick Craver
A: 

You can do the following!

$('#myContainer, #myRadio').click(function(event){

    event.stopPropagation(); //This will stop the bubble so it only fires once per element
    switch(event.srcElement)
    {
        case 'HTMLFormElement':
            //The Div / Form
        break;
        case 'HTMLInputElement':
            //The input itself
        break;   
    }
    return false;
})​

Example Here, You will need to add alerts

RobertPitt