I have a scenario where I have multiple checkboxes and corresponding labels. When the answer is correct, I want to change the background color of the selected checkbox and label.
<input type="checkbox" id="a" class="check-with-label" />
<label for="a" class="question_box">
<?php echo $vraag[0]['A'] ?>
</label>
<input type="checkbox" id="b" class="check-with-label" />
<label for="b" class="question_box">
<?php echo $vraag[0]['B'] ?>
</label>
Upon submitting, an ajax call is made to a script to validate the answer.
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
this.css('background-color', 'green');
} else {
this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
The challenge lies in identifying the correct box since upon submission, the 'this' variable refers to the submit button rather than the checked box. There can only be one checkbox selected at a time.
How do I change the background color to green (and red for incorrect answers) based on the selection?
.check-with-label:checked + .question_box {
background-color: orange;
}
background-color:green
(For incorrect, use red
)