Kakitori
Kakitori

Reputation: 913

How to make the function only runs once JS

How to make the function only runs once per button? if clicks in "click me" only works once, and the same for the other buttons.
Order not to put much code, I put an example..: http://jsbin.com/apexod/2/edit

<input type="button" value="click me" onclick="hello('Jhon')"><br>
<input type="button" value="click me1" onclick="hello('Gerard')"><br>
<input type="button" value="click me2" onclick="hello('Kaoru')">
<script>
function hello(id){
    alert("hello "+id);
}
</script>

Upvotes: 0

Views: 590

Answers (3)

Guffa
Guffa

Reputation: 700212

You can send the button element reference along to the function, and remove the event from the button:

<input type="button" value="click me" onclick="hello(this,'Jhon')"><br>
<input type="button" value="click me1" onclick="hello(this,'Gerard')"><br>
<input type="button" value="click me2" onclick="hello(this,'Kaoru')">
<script>
function hello(el, id){
    alert("hello " + id);
    el.onclick = null;
}
</script>

Demo: http://jsfiddle.net/Guffa/CDjGY/

Upvotes: 3

Ravi Hamsa
Ravi Hamsa

Reputation: 4721

Once executed you can override the function with an empty function

function hello(){
     alert("hello " + id);
     hello = function(){}
}

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

A solution would be to register what buttons have been clicked :

<script>
var done = {}
function hello(id){
   if (done[id]) return;
   done[id] = 1; 
   alert("hello "+id);
}
</script>

(another one would be to use a utility lib like jQuery and its one function but this would be overkill for just that)

Upvotes: 4

Related Questions