Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

372
Visualizações
jQuery - changing div background-color depending on answer

I want to change background-color according to answer I hide the correct answer in the label inside the page.

 <label id="correctanswer" name="1" class="rb" style="display:none;">Tom</label>
 <label id="correctanswer" name="1" class="rb" style="display:none;">Liza</label>

I have 2 questions in the code (please check the jsfiddle)

I want to change the background color of the answers after the user clicks the "Submit" button after marking the relevant answer.

But even if the user chooses the correct answer, the background color get red.

Also, I don't want it to look like this.

Only the background of the answer chosen by the user should be green or red, other colors should not change.

I want it to look like this.

Please check the codes;

http://jsfiddle.net/p9vgcuae/2/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is messy but it works, should give you a more logical approach.
Basically looping through all the checked inputs and comparing user inputs to their correct answer, then changing their background color...

$('#correctAnswer').click(function() {
  var checkedInputs = $(this).parents().find(":checked")
  checkedInputs.each(function() {
    var answer = $(this).parent().parent().parent().find('#correctanswer').text()
    if ($(this).val() === answer) {
        $(this).parent().addClass('confirmed')
    } else {
        $(this).parent().css('background-color','red')
    }
  })
});

I suggest you use data attributes instead of classes and ids to improve your organization

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda