Darcy Darcy - 6 months ago 15
HTML Question

PHP pass total value of radio button

How to count the total value of radio button within the same page and pass to another php file? The total will be count at this page and i can get the total from answer.php file.

<form action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>

Answer

Using jQuery- it is easy, just iterate through the inputs and tally up the values. Note that I gave the form an Id so it can be targetted directly if you have other form. The total can be passed to your other page - either via AJAX or using a standard HTML form as a hidden field. Alternatively - since this is a form and you are already passing it to a PHP page - you could simply submit the form and tally up the $_POST variables on the other side.

$('#testForm input').on('change', function() {
   var total=0;
  $('input[type=radio]:checked', '#testForm').each(function(){
    total += parseInt($(this).val());
    })
  alert(total)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form  id="testForm" action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit"  value="submit" name="submit"/>
</form>

Comments