StabDev StabDev - 5 months ago 16
jQuery Question

Change checkbox + label jquery

I got multiple checkboxes and labels and 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>


and when the user presses submit it calls an ajax call to a script to check if it is the correct answer or not.

$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
//var selected_box = this;
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');
//selected_box.css('background-color', 'green');
} else {
this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});


problem is I don't know how to call the correct box because when the user presses submit the
this
variable is now the submit button and not the checked box (There can only be one checkbox selected at the time_.

So the question is how do I replace the background color of the selected AND the correct box from

.check-with-label:checked + .question_box {
background-color: orange;
}


to

background-color:green


(and for incorrect
red
)

Answer

Try changing the label instead of this

You've already got the ID of the label

(var selected = $(this).attr('id');)

Which will probably return a/b/c/d and then use

$('label[for="'+selected+'"]').css('background-color', 'green'); //or red in the else statement

this styles the label for the selected id, in this case d the code above basicly means:

$('label][for="d"].css('background-color','green'); //or red

but then using the chosen variable

Goodluck!

Comments