Remove attribute onclick by JavaScript

1

Good afternoon, I would like to know how to remove the onClick from the input using the very function that is 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 one of these inputs the onClick function would activate and at the end of the function cause this clicked input to lose the onClick function, change the class to adduser2 and win the value = Success.

by clicking on the first input as follows:

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

Thank you!

    
asked by anonymous 28.07.2016 / 19:31

2 answers

6

Here is an example of how to remove the onclick attribute with jQuery within 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><inputtype="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">
    
28.07.2016 / 19:35
5

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

Why Inline CSS And JavaScript Code Is Such A Bad Thing

Now let's look at an example without jQuery to complement Michael'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>
    
28.07.2016 / 19:42