Key event processing : return value

M

mailpitches

X-No-Archive: yes
From javascript examples I learned that when you set an onkey event to
a function, the return value of the function is a boolean. What does
this boolean value mean?

Example: <body
onload="document.getElementById('field').onkeydown=function(x) { /* do
something */; return false; };">

Bonus question: What search keywords could I use to find this
information ; all my searches turned up nothing.

Thanks!
 
R

RobG

X-No-Archive: yes

a function, the return value of the function is a boolean. What does
this boolean value mean?

This goes back to the original Netscape days and can probably be
classed as DOM 0. If an event handler returns false, the default
action is cancelled[1] for the element that initiated the event. The
value is used by the target/source element's intrinsic event handler to
(maybe) cancel or continue with the default action for that element.
Example: <body
onload="document.getElementById('field').onkeydown=function(x) { /* do
something */; return false; };">

In the above case, the result of the keydown event (i.e. putting the
key's value into the input) will be cancelled and you won't be able to
enter anything into the input[2].

A common use is to conditionally submit a form:

HTML:
<form onsubmit="return validate(this);" ...>...</form>

SCRIPT:
function validate(form) {
var isValid = false;
// validation code to set isValid to true if everything
// is valid, otherwise leave it as false
return isValid;
}

However, it doesn't stop the event propagating and can be very
unreliable in cross-browser applications. You should really only use
it for form submission and to stop link navigation, e.g.

<a href="http://www.blah.com"
Bonus question: What search keywords could I use to find this
information ; all my searches turned up nothing.

"javascript event return false" should do OK. There some good stuff at
Quirksmode:

<URL: http://www.quirksmode.org/js/events_early.html >


1. The usual caveats apply: scripting must be enabled and the browser
must support this aspect of the Netscape event model - not all browsers
do.

2. Some browsers will not cancel the default action at all, others will
do so only in certain cases, and others always.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top