Tuesday, April 10, 2012

JQuery Radio Button Value Check

I need to have the number of 'yes's' selected from a set of radio buttons shown in a hidden field.



I have a form with several sets of radio buttons.



The first radio set:



    <input type="radio" name="number_of_sets_to_count" id="number_of_sets_to_count_1" value="1">
<input type="radio" name="number_of_sets_to_count" id="number_of_sets_to_count_2" value="2">
<input type="radio" name="number_of_sets_to_count" id="number_of_sets_to_count_3" value="3">
<input type="radio" name="number_of_sets_to_count" id="number_of_sets_to_count_4" value="4">
<input type="radio" name="number_of_sets_to_count" id="number_of_sets_to_count_5" value="5">


Subject to the value selected above (ie 1,2,3,4,5) then to calculate the radio buttons selected yes from below radio buttons. ie if selected 2 in radio button above then the first two radio button sets need to check for yes. If 4 selected the the first 4 radio sets below need to be checked for yes values.



This is the next five radio sets



<input type="radio" name="set1" id="set1_no" value="no">
<input type="radio" name="set1" id="set1_yes" value="yes">

<input type="radio" name="set2" id="set2_no" value="no">
<input type="radio" name="set2" id="set2_yes" value="yes">

<input type="radio" name="set3" id="set3_no" value="no">
<input type="radio" name="set3" id="set3_yes" value="yes">

<input type="radio" name="set4" id="set4_no" value="no">
<input type="radio" name="set4" id="set4_yes" value="yes">

<input type="radio" name="set5" id="set5_no" value="no">
<input type="radio" name="set5" id="set5_yes" value="yes">


<input type="hidden" name="number_of_yes" value="">


Thanks to the community help I have this JQuery code that calculates the number of yes's in the form and puts the number into the hidden text box 'number_of_yes' on submit.



<script type="text/javaScript">
$(document).ready(function() {
$("#yourFormsId").submit(function() {
$('input[name="number_of_yes"]').val(
$('input:checked[type="radio"][value="yes"]').length);
});
});
</script>


But, this checks for all yes's selected and I need this limited to the first, second, third, fourth or fifth radio sets (ie set1, set2, set3, set4, set5) depending on what is selected from the number_of_sets_to_count radio button (ie 1,2,3,4,5).



Thanks





No comments:

Post a Comment