Remove onclick attribute by Javascript

Asked

Viewed 1,370 times

1

Good afternoon, I would like to know how to remove onClick from the input using the function itself that is in onClick.

For example, in my case I have the following input:

<input type="submit" class="adduser" onClick="addUser(valor);" value="Adicionar">
<input type="submit" class="adduser" onClick="addUser(valor2);" value="Adicionar">
<input type="submit" class="adduser" onClick="addUser(valor3);" value="Adicionar">

I would like that when the person clicks on one of these inputs the onClick function would activate and at the end of the function cause that clicked input to lose the onClick function, change the class to adduser2 and gain value = Success.

by clicking on the first input:

<input type="submit" class="adduser2" value="Sucesso">

Thank you!

  • Could you improve your question? And if possible put the example code, it helps to understand! ;)

  • @kayoBruno changed the question. See if you’ve gotten better at understanding.

2 answers

6


Here’s an example of how to remove the attribute onclick with jQuery inside the inline referenced function (onclick="..."):

function addUser(valor, ele) {
   console.log('botão com o valor: ' +valor);
   // fazer tudo o que tem para fazer
   $(ele).val('Sucesso');
   $(ele).prop('onclick',null).off('click');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" class="adduser" onClick="addUser(11, this);" value="Adicionar">
<input type="submit" class="adduser" onClick="addUser(22, this);" value="Adicionar">
<input type="submit" class="adduser" onClick="addUser(33, this);" value="Adicionar">

  • I changed my question see if you got better understand. Thank you!

  • Done @rhundler

5

rhundler, first I advise you to read the following article.:

Why Inline CSS And JavaScript Code Is Such A Bad Thing

now let’s go to an example without jQuery to complement Miguel’s response.

var onDoSomethingClick = function (event) {
  alert("button#" + event.target.id + " clicado");
  event.target.removeEventListener("click", onDoSomethingClick);
}

var buttons = document.getElementsByClassName("doSomething");
[].forEach.call(buttons, function (button, indice) {
  button.addEventListener("click", onDoSomethingClick);
});
<button id="btn1" class="doSomething">Botão 1</button>
<button id="btn2" class="doSomething">Botão 2</button>
<button id="btn3" class="doSomething">Botão 3</button>
<button id="btn4" class="doSomething">Botão 4</button>
<button id="btn5" class="doSomething">Botão 5</button>

Browser other questions tagged

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