I'm using jQuery 3.5.1. I have this HTML
<form>
<div><input type="radio" id="radio0" name="choice" >Text1</div>
<div><input type="radio" id="radio1" name="choice" >Text2</div>
<div><input type="radio" id="radio2" name="choice" >Text3</div>
<div><input type="radio" id="radio3" name="choice" >Text4</div>
I want to change the labels next to the radio buttons, so I do this ...
for (let i=0; i<choices.length; i++) {
$('#radio' + i).text(choices[i]);
$('#radio' + i).val(choices[i] == age ? CORRECT : INCORRECT);
$('#radio' + i).attr("checked", false);
}
However, the new labels do not appear on screen. When I inspect the elemnts in Firefox (on Mac), I see this
<div><input type="radio" id="radio0" name="choice" value="incorrect">27
Text1</div>
<div><input type="radio" id="radio1" name="choice" value="incorrect">24
Text2</div>
<div><input type="radio" id="radio2" name="choice" value="incorrect">21
Text3</div>
<div><input type="radio" id="radio3" name="choice" value="correct">30
Text4</div>
<div id="feedback" style="display: none;"></div>
<div>
<input type="button" value="Submit" id="submitAnswer">
</div>
So somehow the elements are getting populated (the "27", "24", etc.) but the old elements are also still there ("Text1") and what appears on screen is the "Text-" labels instead of the numbers. What's the right way to structure the HTML/write the jQuery to change the radio button labels?
Radios are far easier to use when wrapped in <label>
since the whole label is target for events.
Then if you add a <span>
to wrap the text it becomes an easy target for DOM queries
const newVals = [111, 444, 777, 999]
newVals.forEach((v, i) => {
const $input = $('#radio' + i).val(v).prop('checked', false);
$input.next('span').text(v);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>
<input type="radio" id="radio0" name="choice" >
<span>Text1</span>
</label>
</div>
<div><label><input type="radio" id="radio1" name="choice" ><span>Text2</span></label></div>
<div><label><input type="radio" id="radio2" name="choice" ><span>Text3</span></label></div>
<div><label><input type="radio" id="radio3" name="choice" ><span>Text4</span></label></div>