Lavinia
Lavinia

Reputation: 263

How can I disable a button in javascript?

I have a button which is enabled at the beginning, but I want to disable it. I need it for a game. If the player chooses to play more, the game starts again, if not, the button "Click on me" should be disabled. Thank you in advance!

Here is my code:

    var y;
    function playAgain()
    {
        y=confirm("PLAY AGAIN?");

        if(y==true)
        {
            alert("Let's play it again!");
            location.reload(true);
        }
        else if(y==false)
        {
            alert("Thank you!\nSee you soon!");
            document.getElementById("button").disabled="disabled";
            //document.getElementById("button").disabled="true";
        }
    }

The HTML code:

<body>
    <input type="button" value="Click on me" onClick="playAgain()"  />
</body>

Upvotes: 0

Views: 235

Answers (3)

Zeke Nierenberg
Zeke Nierenberg

Reputation: 2206

with jquery you can say

$("[type=button]").click(function(){
    $(this).attr("disabled","disabled");
    ... your other code ...
});

Upvotes: 0

David G
David G

Reputation: 96790

You're using document.getElementById("button") but there is no element named button in the HTML.

<input type="button" id="button" value="Click on me" onClick="playAgain()"  />

Also, to disable a button, set its disabled attribute to true (false for otherwise).

document.getElementById('button').disabled = true;

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150010

This will work:

document.getElementById("button").disabled = true;

If your button actually has id="button":

<input id="button" type="button" value="Click on me" onClick="playAgain()"  />

To re-enable the button set .disabled = false;

Upvotes: 4

Related Questions