tags:

views:

75

answers:

2

Why is "return" used in the onclick even handler below, seems to function with or without the return specification in the onclick event for the buttons?

input type="radio" name="radCPUSpeed" value="6 Ghz"
                       onclick="return radCPUSpeed_onclick(2)"

The function does not seem to do anything with it, why do you need return in the input declaration above?

function radCPUSpeed_onclick(radIndex)
   {
       var returnValue = true;
       if (radIndex == 1)
       {
           returnValue = false;
           alert("Sorry that processor speed is currently unavailable");
           // Next line works around a bug in IE that doesn't cancel the
           // Default action properly
           document.form1.radCPUSpeed[radCpuSpeedIndex].checked = true;
       }
       else
       {
           radCpuSpeedIndex = radIndex;
       }
       return returnValue;
   }
+2  A: 

When you return false from any event handler the event will not bubble up. So lets say normally this button will submit a form, when you return false this will not happen. Essentially it will prevent the default action of the event.

ChaosPandion
While it's true that the event does not bubble up, the behavior you described has to do with preventing the default action.
Andrew67
To be clear, the event **does** still bubble, but the part about preventing the default browser action is correct.
Tim Down
+2  A: 

Returning false from an event handler function will prevent the default browser behaviour associated with the event. Returning any other value (including undefined, which is what is returned if no return statement is executed) will not. Importantly, returning false does not prevent the event from bubbling up the DOM tree, and an event handler attached to a node higher up the DOM tree will still be executed.

Note also that this does not apply to event listener functions attached via addEventListener or attachEvent. The return value in such functions has no effect.

Tim Down
Thanks, but why is "return" needed at the beginning of the "onclick=" below:input type="radio" name="radCPUSpeed" value="6 Ghz" onclick="return radCPUSpeed_onclick(2)"
Don
You can imagine the value of an event handler attribute as the body of a function that is called when the event fires. Returning `false` from this function prevents the default browser action.
Tim Down