Reputation: 1
I have created a quiz element, with four options in it.how should I make disabled all option buttons, when any one of them is clicked.
const obj = {
id:1,
correctAns : "Three",
opt:["One","Two","Three","Four"],
question:"There are how many sides in a triangle?"
}
let quesElement = document.getElementById('ques');
let optionsElement = document.getElementById('options');
let scoreElement = document.getElementById('score');
let heading = document.createElement('h2');
heading.textContent=`${obj.question}`;
quesElement.appendChild(heading);
let ans;
let score = 0;
obj.opt.forEach((x)=>{
let button_div = document.createElement('div');
let option = document.createElement('button');
option.classList.add('opt-btn');
option.textContent = `${x}`;
button_div.appendChild(option);
options.appendChild(button_div);
option.addEventListener('click',()=>{
if(x==obj.correctAns){
score+=1;
}
option.disabled = true;//I want to make all option button disabled.
console.log(score);
scoreElement.textContent = `Score: ${score}`
});
})
Upvotes: 0
Views: 37
Reputation: 443
You can use document.querySelectorAll(".opt-btn");
to get a NodeList of all option buttons. Then you can disable every button with a forEach
loop:
optionButtons = document.querySelectorAll(".opt-btn");
optionButtons.forEach((option)=> {
option.disabled = true;
})
Upvotes: 0