Reputation: 39
I'm trying to create a multiple feedback jquery question I need a little help with my if-statement code. I have one correct answer but would like to have a different feedback alert for selecting each wrong answer. I would like it to give a different feed back for each wrong answer. For example, "You selected grey, there is a better answer, please select again." or "you selected black, there is a better answer."
Here is my code so far.
Jquery:
$(function () {
//variable of correct answers
var rules = ['correct'];
//force checkboxes to work like radio buttons
var boxes = $("input[name=q4]:checkbox").click(function () {
boxes.not(this).attr('checked', false);
});
$('.submit4').click(function (e) {
e.preventDefault();
//check correct answers from var above
if ($('input[name=q4]:checked').map(function (i, v) {
return v.id;
}).get().join(',') == rules[0]) {
alert("Correct! Reflective colors should make you more visible at night");
} else {
$('.grey:checked').attr('disabled', 'disabled').removeAttr('checked');
alert("grey is wrong... it might not be bright enough.");
}
});
});
HTML:
<h1> Question </h1>
<p>What is the best color to wear after dark?</p>
<form>
<label>
<input type="checkbox" name="q4" class="grey"></input>grey</label>
<label>
<input type="checkbox" name="q4" class="black"></input>black</label>
<label>
<input type="checkbox" name="q4" class="white"></input>white</label>
<label>
<input type="checkbox" name="q4" class="red"></input>red</label>
<label>
<input type="checkbox" name="q4" id="correct"></input>reflective yellow</label>
<br />
<button class="submit4">Submit</button>
</form>
Upvotes: 1
Views: 1504
Reputation: 16223
In this case, I suggest you use a switch
, something like (just implement your own logic):
$('.submit4').click(function (e) {
e.preventDefault();
//check correct answers from var above
var result;
switch($('input[name=q4]:checked').attr('class')){
case 'grey':
result = "it's grey";
break;
case 'black':
result = "it's black";
break;
case 'white':
result = "it's white";
break;
case 'red':
result = "it's red";
break;
default:
result = 'Correct answer!';
break;
}
alert(result);
});
In this case the switch works by getting the class of the selected checkbox, and you can do whatever you want on each case instead of using a bunch of if/elses...
Jsfiddle demo: http://jsfiddle.net/darkajax/q4rJ8/
Upvotes: 1