Problem:
To obtain the id from a radio button using jQuery on click or without. The jQuery should detect if the value is already set and choose it or choose it upon click.
HTML code (Scenario 1 – no selection is made):
<th><input type="radio" name="itemquestion" id="1" value="11"></th>
<th><input type="radio" name="itemquestion" id="2" value="12"></th>
<th><input type="radio" name="itemquestion" id="3" value="13"></th>
<th><input type="radio" name="itemquestion" id="4" value="14"></th>
<th><input type="radio" name="itemquestion" id="5" value="15"></th>
HTML code (Scenario 2 – selection has been made):
<th><input type="radio" name="itemquestion" id="1" value="11"></th>
<th><input type="radio" name="itemquestion" id="2" value="12" checked="checked"></th>
<th><input type="radio" name="itemquestion" id="3" value="13"></th>
<th><input type="radio" name="itemquestion" id="4" value="14"></th>
<th><input type="radio" name="itemquestion" id="5" value="15"></th>
jQuery code:
$('input[type=radio]', $('#itembuttons')).click(
function() {
var pos = $(this).parent().index() + 1;
$('#itemresponse').val(pos);
}
);
Question:
How can the jQuery be modified so in addition to act on click() also detect which radio button has already been checked on submit and return that id (in this case it’s 2)? In other words, a user can submit the form without clicking a radio button but I want #itemresponse to contain the id value 2.
If you want to be populated before the user clicks on a radio button, you could add this to set the value when the page is loaded: