1
votes

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;
   }
3

3 Answers

4
votes

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.

2
votes

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.

-1
votes

Basically,the value or whatever comes after the '=' sign is a function in case of an event handler. As a reason,return must be used so that the function returns a boolean value to the event handler-onclick,onsubmit etc.

onclick="return radCPUSpeed_onclick(2)

The above code can be interrupted as: onclick="function(){radCPUSpeed_onclick(2)} Therefore,whatever comes after the equal to sign is actually inside a function and a return statement is required.