Can you get Event.preventDefault() if the call has parameters?

Asked

Viewed 111 times

1

I’m doing an operation where I got the call of a method, in this specific case how I could catch the event.preventDefault() form.

<button type="button" class="btn btn-primary" onclick="AdicionarEditarRegistro('@controller','Edit')">Salvar</button>

Example:

function AdicionarEditarRegistro(controller, action) {
  debugger;

  var t = $("input[name='__RequestVerificationToken']").val();
  var urlCompleto = "/" + controller + "/"+ action +"/";
  var formulario = $("#FormularioCompleto");

  alert('pegar o :' + 'event.preventDefault()');
}

1 answer

2


You can pass the event as argument for the function. In Javascript attributes, event is in the scope.

function handle(name, event) {
  console.log(name); // Luiz
  console.log(typeof event.preventDefault); // function
}
<button onclick="handle('Luiz', event)">Clique-me!</button>

As curiosity as you can pass the event, you can also pass this. :)


Alternatively, if you don’t want to use attributes to determine events, you can create data-attributes and use the addEventListener. Something like that:

const button = document.querySelector('button');

button.addEventListener('click', (event) => {
  const name = event.currentTarget.dataset.name;
  
  console.log(name); // Luiz
  console.log(typeof event.preventDefault); // function
});
<button data-name="Luiz">Clique-me!</button>

I personally prefer this second approach, since I let Javascript take care of events, limiting the role of HTML and increasing the separation of responsibilities.

  • Agadeço the help! it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.