Home > Back-end >  Good alternative for deprecated "event.preventDefault()" for inline javascript code
Good alternative for deprecated "event.preventDefault()" for inline javascript code

Time:06-24

<button type="submit"  onclick="if(!window.confirm('aaa'))event.preventDefault();">aaa</button>

This is my original code. PHPStorm is showing that event global variable is deprecated.

I do not want to make a separate function to do what I want but I just want this inline version built into the "onclick" attribute of the button.

Alternative that uses JQuery correctly will be better. Any advice will be appreciated.

EDIT: the linked question has answers that make a separate function. I want an INLINE version that is built into the onclick. I don't want to make my code long.

CodePudding user response:

To start with, you really shouldn't use inline handlers if you want to be writing decent maintainable modern JavaScript. They have a plethora of problems including usually only being able to reference global identifiers (such as window.event). I'd strongly recommend attaching the event handler properly using JavaScript.

$('button').on('click', (e) => {
  if (!window.confirm('aaa')) {
    e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <button type="submit" >aaa</button>
</form>

If that's really not an option for you, it's just barely possible to do what you want by referencing the arguments for the inline handler. The first argument will be the event, so arguments[0].preventDefault() will do what you want.

<form>
  <button type="submit"  onclick="if(!window.confirm('aaa')) arguments[0].preventDefault();">aaa</button>
</form>

  • Related