4

This is my current solution:

html

<input type="checkbox" value="1" onclick="return do_stuff();" />
<input type="checkbox" value="1" onclick="return do_stuff2();" />

javscript:

function do_stuff() {   
    return false;
}

function do_stuff2() {   
    return true;
}

http://jsfiddle.net/NXKMH/12/

I would like to avoid needing the "return" in the onclick call (ex. onclick="do_this();" instead of onclick="return do_this();"). I thought about using the preventDefault() function that jquery provides, but cant seem to get that working. Also, I dont want to bind "click" event if possible. I prefer using the "onclick". (easier to work with ajax loaded content)

Thoughts?

Roeland
  • 3,698
  • 7
  • 46
  • 62
  • `return false` and `preventDefault` work only if you use jquery `click` event. – jcubic Mar 21 '13 at 17:53
  • you can't use `event.preventDefault` providied by jQuery unless you actually use jQuery for the event. You could use the native version of it, but it's located in one place for modern browsers, and another for old ie. `return false` is so much simpler. – Kevin B Mar 21 '13 at 18:02

2 Answers2

8

The return value of an event handler determines whether or not the default browser behaviour should take place as well.

So ...

onclick='function(); return false;' 

should fix it ...

Radiotrib
  • 629
  • 5
  • 8
5

Have you tried calling the event.stopPropagation() method inside do_stuff() ... you'll need to pass in the event of course.

onclick = 'do_stuff(event)'

function do_stuff(ev) {

  if(ev.stopPropagation) {
    // for proper browsers ...
    ev.stopPropagation();
  } else {
      // internet exploder uses cancelBubble ...
      window.event.cancelBubble = true;
  }
  // --- do some more stuff ---//
}
Radiotrib
  • 629
  • 5
  • 8