How to unbind a listener that is calling event.preventDefault() (using jQuery)?

Viewed 251793

jquery toggle calls preventDefault() by default, so the defaults don't work. you can't click a checkbox, you cant click a link etc etc

is it possible to restore the default handler?

20 Answers

It is not possible to restore a preventDefault() but what you can do is trick it :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

If you want to go a step further you can even use the trigger button to trigger an event.

If the element only has one handler, then simply use jQuery unbind.

$("#element").unbind();

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.

window.onKeydown = event => {
    /*
        if the control button is pressed, the event.ctrKey 
        will be the value  [true]
    */

    if (event.ctrKey && event.keyCode == 83) {
        event.preventDefault();
        // you function in here.
    }
}

in javacript you can simply like this

const form = document.getElementById('form');
form.addEventListener('submit', function(event){
  event.preventDefault();

  const fromdate = document.getElementById('fromdate').value;
  const todate = document.getElementById('todate').value;

  if(Number(fromdate) >= Number(todate)) {
    alert('Invalid Date. please check and try again!');
  }else{
    event.currentTarget.submit();
  }

});

Worked as the only method to restore the default action.

$('#some_link').unbind();

This should work:

$('#myform').on('submit',function(e){
    if($(".field").val()==''){
        e.preventDefault();
    }
}); 
Related