简体   繁体   中英

How to make function work only once even when button is clicked twice?

OK, guys. I am trying to create a tip calculator, and I came across some problems. The thing is when the user enters a value, the program will ask(disabling the enter button) if the user wants to include the tip, so the user chooses yes or no. If either is chosen, the previous question disappears and the text appears "Tip is included" or "Tip is not included". Now, if the user wants to edit the value above, the button will get enabled again but if it clicked one, it will again ask whether the user wants to include the tip. SO my question is how can I make it so that no matter how many times that button is clicked, that function(asking tip) works only once?

Here is some code, HTML

<h3>What is the bill?</h3>
<input type="number" id="bill" autocomplete="off">
<button id="enterTheBill">Enter</button>
<div id="askTip">
    <h3> Would you like to include the tip?</h3>
    <button id="yesTip">Yes</button>
    <button id="noTip">No</button>
</div>
<h3 id="includedTip">*Tip is included*</h3>
<h3 id="excludedTip">*Tip is NOT included*</h3>

Javascript:

document.getElementById('enterTheBill').onclick = askForTip
function askForTip() {
    document.getElementById('askTip').style.display = 'block'
    document.getElementById('enterTheBill').disabled = true
}

document.querySelector('#bill').onchange = enableButton
function enableButton() {
    document.getElementById('enterTheBill').disabled = false
}

You can define a global variable (flag) above the askForTip function and can set that toggle that flag on the first execution of askForTip and next while executing askForTip, you can check whether to stop or execute code depending upon the flag.

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