Ad

How To Calculate A Total By Taking The Radio Button Values Using PHP And Javascript?

I represent the questions from the database using php. Using an array I display them in a table. The radio buttons are grouped by giving a variable "i" in php as the name. Because of that I cannot get the values of those radio buttons to a javascript function to calculate the total.

This is how the table is represented:

This is how the table is represented

I want to calculate the total from the selected radio button values and send the value to another page. How do I do that? Thanks a lot in advance!

Below is my code.

<html>

<body>

 <?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'psych';

$connect = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);

    $res = mysqli_query($connect, "SELECT questions FROM questions");

    $quests = mysqli_fetch_array($res);  

  ?>
<form name="form1" id="form1" method="post" action="../../Algorithms/score.php"> 

<table> 
  <th>
  <td width=100>Strongly agree </td>
  <td width=100>Agree </td>
  <td width=100>Neutral </td>
  <td width=100>Disagree </td>
  <td width=100>Strongly disagree </td>
  </th>
<?php 

$score=0;

    $i=1;
  while($row = mysqli_fetch_array($res))
    {
     echo "<tr> <td width=500>".$i.". ".$row['questions']."</td>";
     echo '<td width=100> <input type="radio" name="'.$i.'"  value="1" > </td>';
     echo '<td width=100> <input type="radio" name="'.$i.'"  value="2" > </td>';
     echo '<td width=100> <input type="radio" name="'.$i.'"  value="3" > </td>';
     echo '<td width=100> <input type="radio" name="'.$i.'"  value="4" > </td>';
     echo '<td width=100> <input type="radio" name="'.$i.'"  value="5" > </td>';
       // if (score."$i") {echo "score$i";}
     echo "</tr>"; 
     // echo $scores[$i];
     //$scores[$i]=$_POST['score'.$i];
     $i++;

      }

    echo "</table>"; 
    echo "<br>"; 

  ?> 

  <input type='submit' name='submit' value='Submit'/>    

Ad

Answer

First of all , it will better to name your inputs with a meaningful names.

For example

echo '<td width=100> <input type="radio" name="score['.$i.']"  value="1" > </td>'

this will help you to distinguish between other fields - if you need to add another fields -

in server side , you are now have a array of inputs called score , you can sum/calculate the total with array_sum just like :

if (isset($_POST['score'])) {
    $total = array_sum($_POST['score']);
}

to save this value , you can use session with this

Ad
source: stackoverflow.com
Ad