I have a page with a multiple choice question. If the user selects the correct answer, I would like the explanation under their choice to turn from grey to green. I have only been able to get all the choices to turn green, no matter what is selected, and can't seem to get this right. Help is much appreciated, thanks.
html
<li class='test-questions'>
<input data-correct="true" id="answer_id_1" name="answer_id" type="radio" value="1" />
A) I am the correct answer!
<div class='question_explanation'>
<p>Correct. This is an explanation of the correct answer.</p>
</div>
</li>
<li class='test-questions'>
<input data-correct="false" id="answer_id_2" name="answer_id" type="radio" value="2" />
B) I am an incorrect answer.
<div class='question_explanation'>
<p>Incorrect. This is an explanation why the answer is incorrect.</p>
</div>
</li>
css
div.question_explanation {
background-color: LightGray;
}
div.correct_answer_green {
background-color: LightGreen;
}
bad javascript/jquery function
$("input[name*='answer_id']").each(function() {
if ($(this).data('correct') === true && $(this).is(':checked')) {
$('div.question_explanation').addClass('correct_answer_green');
}
});
the same bad function in coffeescript if you prefer
$("input[name*='answer_id']").each ->
if $(this).data('correct') == true and $(this).is(':checked')
$('div.question_explanation').addClass 'correct_answer_green'
return
Use
//Bind change event
$("input[name*='answer_id']").change(function() {
//If condition
if ($(this).data('correct') === true && $(this).is(':checked')) {
$(this)
.closest('li') //Find parent li
.find('div.question_explanation') //find your div
.addClass('correct_answer_green');
}
}).trigger('change'); //Trigger on page load
$(document).ready(function() {
$("input[name*='answer_id']").change(function() {
if ($(this).data('correct') === true && $(this).is(':checked')) {
$(this).closest('li').find('div.question_explanation').addClass('correct_answer_green');
}
}).trigger('change');
});
div.question_explanation {
background-color: LightGray;
}
div.correct_answer_green {
background-color: LightGreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class='test-questions'>
<input data-correct="true" id="answer_id_1" name="answer_id" type="radio" value="1" />A) I am the correct answer!
<div class='question_explanation'>
<p>Correct. This is an explanation of the correct answer.</p>
</div>
</li>
<li class='test-questions'>
<input data-correct="false" id="answer_id_2" name="answer_id" type="radio" value="2" />B) I am an incorrect answer.
<div class='question_explanation'>
<p>Incorrect. This is an explanation why the answer is incorrect.</p>
</div>
</li>
</ul>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments