1

I have problem with javascript, in my html code:

<input onclick="myFunction();" />

<script>
function myFunction(){
 //excecution of this fucntion
}
</script>

After clicking the input, the function runs. But I want myFunction to be disable after the first click, so when I click again, myFunction won't run.

1
  • pass this to myFunction and at the end do this.disabled=true; Commented Mar 1, 2015 at 13:11

4 Answers 4

2

Just remove the attribute

<input onclick="myFunction(this);" />

<script>
function myFunction(elem){
    // code here
    elem.removeAttribute('onclick')
}
</script>

or even better use event listeners

<input id="myInput" />

<script>
    document.getElementById('myInput').addEventListener('click', myFunction, false);

    function myFunction(elem){
        // code here
        this.removeEventListener('click', myFunction);
    }
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

I wouldn't remove the attribute (not even sure whether that works) but do this.onclick = null
@Bergi - Removing the attribute works just fine in all browsers, it automatically also removes the property as inline on... attributes are mapped to the property. Of course, using addEventListener is much easier in my opinion
Yeah, addEventListener should be preferred, +1
1

One way is to set it to a empty function, after the code has executed.

function myFunction(){
   //(..) Some code
   myfunction = function(){}; // empty the function so nothing happens next time
}

2 Comments

@VinraGunantaPandia yes. That's what you want right?
not exactly, but sometimes i neet to reactivated it
1

If you're using jQuery (as You have included it in the tags), I'd go with .one():

<input type="txt" class="my-input" />


function activateClick(){
    // single click:
    $('.my-input').one('click', function(){
        // do stuff ...
    });
}

// Activate single click on input element 
// Can be reactivated later on, using the same function (see DEMO):
activateClick();

DEMO

Comments

0

Use a boolean indicator to determine whether the function has already run or not. The advantage with this method is that it is easy to reset the function status at a later date.

<!DOCTYPE html>
<html>
<body>
<button onclick='func();'>Function</button>
</body>
<script>
var funcActive=true;
function func() {
if (funcActive) {
funcActive=false;
alert('func ran');
}
}
</script>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.