简体   繁体   中英

How can I disable an HTML button until another button is clicked?

I'm trying to make a game where you enter a number into a textbox and then click on Lock In .

You can then not change your answer.

After that you click on Random Number and it will give you a random number 1-50 .

But the problem is that I want to make it where you have to click Lock In before you can find out the random number.

This is because you can just not click Lock In and then change it so that it is right.

My code for this is below:

 function numFunction() { var x = Math.floor((Math.random() * 50) + 1); document.getElementById("randnum").innerHTML = x; start.disabled = true; reload.disabled = true; } function btnFunction() { document.getElementById("answerbox").readOnly = true; } function revFunction() { document.getElementById("rnum").disabled = false; } 
 <div id="randbutton"> <button id="rnum" onclick="numFunction()">Random Number</button> <p id="randnum"></p> <input type="text" name="answerbox" size="20" id="answerbox"> <div id="lockbtn"> <button onclick="btnFunction();revFunction();">LockIn</button> <div id="resetbtn"></div> <button id="relbtn" onclick="relFunction()">Reset</button> </div> </div> 

You are really close. You can just add "disabled" to your button, and then when the user locks in their answer, enable it again.

Additionally, it's not best practice to split your JavaScript into a bunch of different script tags. Put them all in one place.

 function numFunction() { var x = Math.floor((Math.random() * 50) + 1); document.getElementById("randnum").innerHTML = x; start.disabled = true; reload.disabled = true; } function btnFunction() { document.getElementById("answerbox").readOnly = true; } function revFunction() { document.getElementById("rnum").disabled = false; } function relFunction() { location.reload(); } 
 <div id="randbutton"> <button id="rnum" onclick="numFunction()" disabled>Random Number</button> <p id="randnum"></p> <input type="text" name="answerbox" size="20" id="answerbox"> <div id="lockbtn"> <button onclick="btnFunction();revFunction();">LockIn</button> <div id="resetbtn"></div> <button id="relbtn" onclick="relFunction()">Reset</button> </div> </div> 

you could use the disabled property on the button to start.

<button type="button"id="lock" onclick="enableNum()">Lock in</button>
<button type="button"id="randomNum" disabled>Random Number</button>

Then when someone enters the number, you would have a function that detects the input and enables the button.

function enableNum() {
document.getElementById("randomNum").disabled = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM