Home > Blockchain >  jQuery - changing div background-color depending on answer
jQuery - changing div background-color depending on answer

Time:03-04

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"  style="display:none;">Tom</label>
 <label id="correctanswer" name="1"  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/

CodePudding user response:

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

  • Related