JPB JPB - 1 year ago 89
Javascript Question

Set hidden input value depending on radio button selection

I have a checklist form that tallies a score based on the radio button selection that is working fine. When I post the form I want to get a value of "yes" or "no" from a hidden input with the same class based on radio button selection.

Because the "value" field is taken up by an integer for the scoring I want to pass a value to a hidden form input with the same class name. The value of the hidden input will be "no" if the value of the radio button selected is 0, or else it will be "yes".

I would like to be able to iterate it through all radio input groups (there are many). This is what I am trying to acheive in jquery written in English:

FOR each radio input group, IF the value of radio button selected is 0 then value of hidden input with the same class is "No", ELSE it is "yes".

I am having trouble with the javascript and would appreciate some assistance.


<!--Radio button example -->
<label>Does 1 + 1 equal 10 ?</label>
<input type="radio" class="radio1" name="question" value="1">Yes</input>
<input type="radio" class="radio1" name="question" value="0">No</input>
<input type="hidden" value="" id="answer" class="radio1"></input>

Thank you in advance, please let me know if you need more information.

Joe Joe
Answer Source
$("input[type='radio']:checked").each(function(i, element) {
      var hiddenVal = $(element).value() === "0" ? "No" : "yes"
      $("." + $(element).attr("class") + "[type='hidden']").val(hiddenVal);