1

Let's assume there is this form on a website:

<form method="post" action="/cart">
<!--Some inputs here-->
<button type="submit" name="checkout">Checkout</button>
</form>

And this javascript code I use to change form button behavior:

setInterval(function(){
  $("*").off()
  $(document).on('click',"*",function(e){  
      alert(1)
      e.preventDefault(); 
  });
  jQuery('*').unbind().submit(function(e) {       
      return false;
  })
}, 1);

This is just as example, I know I should not use interval and * selector. Since selector * is used (just for testing), I can exclude the selector is not correct. By using interval (just for testing) I can exclude option that bind is used later.

Theoretically without real example, what could cause that off and click event are still ignored?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
John Clark
  • 59
  • 8
  • What do you expect the code to do and what does actually happen? – Felix Kling Sep 15 '19 at 16:50
  • I expect the code to remove all events attached to this form button and trigger alert(1). But it doesn't, it still processes the form in old way and ingores my code. – John Clark Sep 15 '19 at 16:51
  • @JohnClark are you sure, I tried it and it exploded with a bajillion alerts when I tried it. Probably because there is one attached every time the `setInterval` callback is invoked which, in turn, would be multiple times per second. I'm not sure why you use an interval, though. – VLAZ Sep 15 '19 at 17:12
  • Yes of course it works if you try it alone, what I am trying to find out is why it doesn't work if I put this code in console when I am on the website which has many javascript files included. I can not give url, this is why I am asking what could theoretically prevent this code to not work. I thought $("*").off() would remove all events and won't allow form to be submitted. But I am wrong. Are in javascript there other things beside events that could make some action on button click/submit? – John Clark Sep 15 '19 at 17:20
  • 1
    I think I found answer. I assumed I can remove events created with addEventListener with jQuery, apparently you can not. jQuery can only unbind all event handlers for a given event if the original listeners were configured using jQuery. I guess I need to use native js function removeEventListener and I won't be able to unbind events with jquery. – John Clark Sep 15 '19 at 17:39
  • See [here](https://stackoverflow.com/questions/41715451/does-jquery-off-method-remove-event-listeners-added-with-addeventlistener) – trincot Sep 16 '19 at 09:12

0 Answers0