Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to prevent default action when using "onclick" of a checkbox? [duplicate]

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?

like image 244
Roeland Avatar asked Dec 16 '22 12:12

Roeland


1 Answers

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 ---//
}
like image 151
Radiotrib Avatar answered Jan 25 '23 11:01

Radiotrib