Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
How do I make only one button can be selected at time?

document.querySelectorAll(".answer").forEach((answer) => {
    //getting .answer from HTML and adding a click function
    answer.addEventListener("click", (event) => {
        if (event.target.dataset) {
            document.querySelectorAll(".answer").forEach(e => e.classList.remove('selected'))
            answer.classList.add('selected')
        }
        if (event.target.dataset.correct == "true") {
            correctAnswer++
        }
    });
});
.selected{
    border: 5px solid black;
}
        <h3 id="question"></h3>
        <div class="answers">
            <button type="button" id="answer1" class="answer"></button>
            <button type="button" id="answer2" class="answer"></button>
            <button type="button" id="answer3" class="answer"></button>
            <button type="button" id="answer4" class="answer"></button>
        </div>

I have my question and answers in an object, they are shuffled and the answers are put into these buttons, then the selected button get a border. How do I make it where only one button can be selected at a time, and if 2 are selected, the first one is unselected.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It's better to use a class to apply these styles.

Simply remove the class from every element before adding the class to the current element.

document.querySelectorAll(".answer").forEach((answer) => {
    //getting .answer from HTML and adding a click function
    answer.addEventListener("click", (event) => {
        if (event.target.dataset) {
            document.querySelectorAll(".answer").forEach(e => e.classList.remove('selected'))
            answer.classList.add('selected')
        }
        if (event.target.dataset.correct == "true") {
            correctAnswer++
        }
    });
});
.selected{
  border:5px solid black;
}
<h3 id="question"></h3>
        <div class="answers">
            <button type="button" id="answer1" class="answer">1</button>
            <button type="button" id="answer2" class="answer">2</button>
            <button type="button" id="answer3" class="answer">3</button>
            <button type="button" id="answer4" class="answer">4</button>
        </div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!