I am having an error where my JQuery works initially upon radio click, but after toggling the radio buttons a few times, it breaks.
What is the proper way to update page text in CSS with 2+ radio questions using JQuery? The toggling of the multiple radio buttons (upon user click) should work indefinitely as it’s a simple, basic if condition.
Code:
var q1 = $("input[name=q1]:radio");
var q2 = $("input[name=q2]:radio");
var q3 = $("input[name=q3]:radio");
var a1 = "foo";
var a2 = "bar";
var aa = "bas";
q1.change(function () {
$("input:checked").each(
function () {
if ($(this).val() == "Yes") {
$("#a1").text(a1);
} else {
$("#a1").text("");
};
}
);
})
q2.change(function () {
$("input:checked").each(
function () {
if ($(this).val() == "Yes") {
$("#a2").text(a2);
} else {
$("#a2").text("");
};
}
);
})
.change();
HTML
Question 1 Here?<br />
<input type="radio" name="q1" id="q1-y" value="Yes" />Yes
<input type="radio" name="q1" id="q1-n" value="No" />No
<br />
Question 2 Here?<br />
<input type="radio" name="q2" id="q2-y" value="Yes" />Yes
<input type="radio" name="q2" id="q2-n" value="No" />No
<br />
Question 3 Here?<br />
<input type="radio" name="q3" id="q3-y" value="Yes" />Yes
<input type="radio" name="q3" id="q3-n" value="No" />No
<div id="a1"></div>
<div id="a2"></div>
<div id="a3"></div>
<div id="aa"></div>
I’d like to insert text into the Divs based on what is checked in the radio buttons. As mentioned above, the JQuery appears to work initially, but after 3+ clicks, the if statements don’t work.
Thanks
The problem lies in these lines:
This means the condition of every checked input is being used to determine what should be displayed, when it should only be one set of radio buttons informing the decision. The problem doesn’t appear until multiple radio button sets have been checked. A quick fix is to say:
and similarly for each change handler.