1

When calling a JavaScript function what does the return value do to an input form field? For example:

<script type="text/javascript">
 function foo()
 {
  return true;
 }
</script>
<input type="text" id="txt1" onkeyup="return foo()" />

and variations, IIRC onkeyup="foo(); return false"
I don't really need a return time, what's the easiest way to do this?

Right now I'm trying to call multiple functions from one event and not sure what the appropriate way is: <input type="text" id="txt1" onkeyup="return foo1(); return foo2();" or
<input type="text" id="txt1" onkeyup="return foo1()" onkeyup="return foo2();"

Celeritas
  • 14,489
  • 36
  • 113
  • 194
  • 1
    If you don't need to return anything then don't do it ;) – Felix Kling Jan 31 '13 at 19:00
  • possible duplicate of [What's the effect of adding 'return false' to an onclick event?](http://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-an-onclick-event) – Felix Kling Jan 31 '13 at 19:01

3 Answers3

2

return false; is used to stop the event from having its default effect (in this case, the letter typed from being added). return foo() is used so that foo can be the judge of whether to return true or return false and therefore whether or not the default action should happen.

If you are just calling a function that won't affect whether or not the event actually takes place, just use onkeyup="foo1(); foo2();". If, however, one of them affects the outcome, it should be called last and have a return before it.

In general, though, it's easier to have a single function in there, say onkeyup="return foo()", and then have

function foo() {
    foo1();
    foo2();
    return true; // or whatever
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

The most appropriate way is to bind multiple functions to one event like so:

ELEMENT.addEventListener('onkeyup', function(event) {
    foo();
    bar();
    fooBar();
}, false);

Or to simplify it even further you could use jQuery:

$(element).on({
    keyup: function() {
        foo();
        bar();
        fooBar();
    }
});

*Hint: use this (in jquery) or event.target (non-jquery) to work with the event source.

Martin
  • 461
  • 2
  • 9
0

Ideally you shouldnt be putting them inline AT ALL... you should be using event handlers attached to the dom elements.

for example:

document.getElementById('txt1').addEventListener('onkeyup', function() {
   foo1();
   foo2();
});

Now the caveat here is that event assignment isnt necessarily normalized so you need to attach listeners in different ways in different browsers. This is one of the reasons people use libraries like jQuery - it normalizes all this.

prodigitalson
  • 60,050
  • 10
  • 100
  • 114