简体   繁体   中英

Vanilla Javascript : how to make a button clickable once only

I have a quiz app application that I am working on that dynamically creates 2-4 buttons for the answer. However, if you click on an answer, you can keep clicking on the same answer or keep clicking the other answers. I want the user to be able to click one of the buttons but then not be able to keep clicking. caveat though: when a user clicks one of the buttons, a new "Next" button gets created and that one does still need it's click event.

tl;dr I need dynamically created buttons to be clickable only once but a "Next" button to still be clickable.

Code:

function renderButtons() {
  var answerContainer = document.getElementById("answer-buttons");
  answerContainer.innerHTML = "";

  for (var i = 0; i < 4; i++) {
    var button = document.createElement("button");
    button.classList.add("btn");
    button.setAttribute("id", "answerBtns");
    button.hasAttribute("data-correct");
    button.setAttribute("data-correct", questions[count].answers[i].correct);
    button.onclick = btnclick;
    button.textContent = questions[count].answers[i].text;
    answerContainer.appendChild(button);
  }
}

// if user clicks on button check if true
function btnclick(e) {
  e.preventDefault();
  var value = event.target.dataset.correct;
  scoreBox.textContent = "Score: " + score;
  if (value === "true") {
    score += 5;
    document.body.style.background = "green";
  } else {
    document.body.style.background = "red";
  }

  var next = document.getElementById("answer-buttons");
  var nextBtn = document.createElement("button");
  nextBtn.classList.add("nextBtn");
  nextBtn.textContent = "Next";

  next.appendChild(nextBtn);

  nextBtn.onclick = nextBtnFx;

if you want to see what I'm talking about, the app can be found here: https://andrethetallguy.github.io/Animal-Quiz/

Thanks!!!

In the handler function nextBtnFx you could disable the button with

this.disabled = "true" 

that would make it unclickable after the first click

ref : https://stackoverflow.com/a/17115132/13998159

 <.DOCTYPE html> <html> <head> <title>Button</title> </head> <body> <input type="button" id="btn01" value="OK"> <button onclick="disableElement()">Disable</button> <button onclick="enableElement()">Enable</button> <script> function disableElement() { document.getElementById("btn01");disabled = true. } function enableElement() { document.getElementById("btn01");disabled = false; } </script> </body> </html>

You can use these functions to disable/enable the buttons.

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