Jump to content

calculation


girlzz

Recommended Posts

<script type="text/javascript">

function calculate()

      var cams = document.getElementByName("cam");
  
      var finals = document.getElementByName("final_exam");
  
      var total = 0;
  
      for (i = 0; i < cams.length; i++) {
  
          var total = parseInt(cams[i].value) + parseInt(finals[i].value);
  
    }
  
      document.getElementByName("total").value = total;



</script>

 

i had this code for insert many marks but don't work... can anyone help me

Link to comment
Share on other sites

Well, it's difficult to know exactly what is supposed to happen without seeing the accompanying HTML, but there is a lot wriong with that code.

 

1. The function code should be enclosed in curly braces

2. There is no getElementByName, it is getElementsByName

3. The while loop makes no sense because it is overwriting the value of total on each iterration - because youare reinitiating the variable using var and because you are setting it to a new value

 

Without seeing the HTML that this goes with I can't decide how it should be corrected. Here is a guess

<script type="text/javascript">

function calculate()
{
    var cams = document.getElementsByName("cam");
    var finals = document.getElementById("final_exam");
    var total = 0;

    for (i=0; i<cams.length; i++)
    {
        total += parseInt(cams[i].value) + parseInt(finals[i].value);
    }

    document.getElementById("total").value = total;
}

</script>

Link to comment
Share on other sites

ook this is my php including html coding

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

if(isset($_POST['matric_no']) && sizeof($_POST['matric_no'])>0){
$matric_no = $_GET[matric_no];
$query_mat = "SELECT matric_no FROM medic_exam WHERE matric_no='$matric_no' ";
$mat = mysql_query($query_mat, $mas) or die(mysql_error());
$row_mat = mysql_fetch_assoc($mat);

if ($row_mat)
{
echo("<script type=\"text/javascript\">");
echo("alert('Result already been entered');");
echo("</script>");
} 
else
{
for($i=0;$i<count($_POST['matric_no']);$i++){
$insertSQL = sprintf("INSERT INTO medic_exam (matric_no, sessi, `year`, `group`, s_code, title, cam, final_exam,total,grade) VALUES (%s, %s, %s, %s,%s, %s, %s, %s, %s, %s )",
                       GetSQLValueString($_POST['matric_no'][$i], "text"),                
                       GetSQLValueString($_POST['sessi'], "text"),
                       GetSQLValueString($_POST['year'], "text"),
                       GetSQLValueString($_POST['group'], "int"),
				   GetSQLValueString($_POST['s_code'], "text"),                
                       GetSQLValueString($_POST['s_title'], "text"),
                       GetSQLValueString($_POST['cam'], "int"),
                       GetSQLValueString($_POST['final_exam'], "int"),
				   GetSQLValueString($_POST['total'], "int"),
                       GetSQLValueString($_POST['grade'], "text"));
				   
mysql_select_db($database_mas, $mas);
$Result = mysql_query($insertSQL, $mas) or die(mysql_error());					 
$saved = true;
}
}
}               
$colname_test = "-1";
if (isset($_GET['s_code'])) {
  $colname_test = $_GET['s_code'];
}

$session =$_GET['session'];
  $year = $_GET['year'];

if ($session ==0)
{
echo("<script type=\"text/javascript\">");
echo("alert('Data not found.Please enter the required data.');");
echo("window.location=\"exm.php\"");
echo("</script>");
} 
if ($year ==0)
{
echo("<script type=\"text/javascript\">");
echo("alert('Data not found.Please enter the required data.');");
echo("window.location=\"exm.php\"");
echo("</script>");
}


mysql_select_db($database_mas, $mas);
$query_test = sprintf("SELECT * FROM medic_registered_course WHERE s_code = %s", GetSQLValueString($colname_test, "text"));
$test = mysql_query($query_test, $mas) or die(mysql_error());
$row_test = mysql_fetch_assoc($test);
$totalRows_test = mysql_num_rows($test);

if ($totalRows_test==0)
{
echo("<script type=\"text/javascript\">");
echo("alert('Data not found.Please enter the required data.');");
echo("window.location=\"exm.php\"");
echo("</script>");
}

mysql_select_db($database_mas, $mas);
$s_code=$_GET[s_code];
$search=$_GET[search];
$year= $_GET[year];
$sessi= $_GET[session];
$query_test = "SELECT * FROM medic_registered_course WHERE medic_registered_course.s_code='$s_code' AND medic_registered_course.group='$search' and year= '$year' and sessi = '$sessi' ";
$test = mysql_query($query_test, $mas) or die(mysql_error());
$row_test = mysql_fetch_assoc($test);

if ($row_test==0)
{
echo("<script type=\"text/javascript\">");
echo("alert('Data not found.Please enter the required data.');");
echo("window.location=\"exm.php\"");
echo("</script>");
}

mysql_select_db($database_mas, $mas);
$query_Recordset2 = sprintf("SELECT medic_subject_offered.s_code, medic_subject_offered.s_title FROM medic_subject_offered WHERE medic_subject_offered.s_code LIKE  '%%%s%%'" , $colname_test);
$Recordset2 = mysql_query($query_Recordset2, $mas) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$totalRows_Recordset2 = mysql_num_rows($Recordset2);

if ($totalRows_Recordset2==0)
{
echo("<script type=\"text/javascript\">");
echo("alert('Data not found.Please enter the required data.');");
echo("window.location=\"exm.php\"");
echo("</script>");
}

?>
<html>
<head>
<title>List Registered Subject | Medic Assessment System</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="keywords" content="Keywords here">
<meta name="description" content="Description here">
<meta name="Author" content="Joseph De Araujo">
<meta name="Publisher" content="MyFreeTemplates.com">
<meta name="robots" content="index, follow"> <!-- (robot commands: all, none, index, no index, follow, no follow) -->
<meta name="revisit-after" content="30 days">
<meta name="distribution" content="global">
<meta name="rating" content="general">
<meta name="content-language" content="english">
<title>Class List View | Medic Assessment System</title>
<script language="JavaScript" type="text/JavaScript" src="images/myfreetemplates.js"></script>

<style type="text/css">
<!--
.basestyle {
color: #FFFFFF;
font-size: 10px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
h1 {
font-size: 16px;
font-weight: bold;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
body, td, p, input {
font-size: 11px;
font-family: Verdana, Arial, Helvetica, sans-serif;
color: #333333;
}
.navlinks {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
color: #FFFFFF;
}
.style6 {
font-size: 12px;
color: #000000;
font-weight: bold;
}
.style7 {
font-size: 12px;
font-weight: bold;
}
.style10 {color: #000000}
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: none;
}
a:active {
text-decoration: none;
}
.style11 {color: #000000; font-size: 12px;}
.style12 {font-weight: bold}
.style13 {
font-size: 12px;
color: #000000;
background-color: #D6D6D6;
height: 22px;
width: 72px;
outline: 1;
border: 1;
font-weight: normal;
}
.style15 {font-size: 11px; font-family: Verdana, Arial, Helvetica, sans-serif; }
-->
</style>

<script type="text/javascript">

function calculate()

{

var total = (parseInt(document.getElementById("cam").value) + parseInt(document.getElementById("final_exam").value)) / 2;

if (total >100)
{
alert('Total cannot be more than 100.!!');
}
else if (total<0)
{
alert('Total cannot be negative.!!');
}
else
{
document.getElementById("total").value = total;
var grade;

if (total>=80)
{
grade = 'A';
}

else if(total>=70)
{
grade = 'B';
} 
else if(total>=60)
{
grade = 'C';
}
else if(total>=50)
{
grade = 'D';
}
else if(total>=40)
{
grade = 'E';
} 
else
{
grade = 'F';
}

document.getElementById("grade").value = grade;
}
}

</script>

<script src="../../../Scripts/AC_RunActiveContent.js" type="text/javascript"></script>
</head>
<body style="margin:0; background-color: #E4E7E6;" <?php if($saved){echo 'onload="alert(\'Records successfully saved.\');"';}?>>

<table width=1097 height="100%" border=1 align="center" cellpadding=0 cellspacing=0>
       
        <tr align="center" valign="middle">
          <td height="34" colspan="2" class="style11">You are here>><a href="main.php">Main Menu</a> >>Examination>>Insert Result </td>
  </tr>
<tr>
  <td width="202" height = "90%"valign="top"><div align="center" class="style6">
    <p class="style30">ASSALAMUALAIKUM</p>
    </div>
    <div align="center" class="style7">	      EXAMINATION</div>	  
	<ul>
	  <li><span>
      <a href="exm.php">Insert Result
      </a></span>		    </li>
    </ul>
	<p><span class="style7"><a href="<?php echo $logoutAction ?>">>>LOGOUT</a></span> </p>
	<p align="center" class="style7">Date: <?php echo date('d-m-Y') ."\n";?></p></td> 
      <td width="889" valign="top" style="padding-left:20px; padding-top:25px; padding-right:40px; padding-bottom:35px; "><p>
 <form id="form2" name="form2" method="post" action="">
  <p align="center" class="style12 style28 style29"><strong>LIST REGISTERED SUBJECTS</strong></p>
  <p align="center" class="style12"> </p>
  <blockquote>
    <blockquote>
                                <blockquote>
                                  <blockquote>
                                    <p> </p>
                                    <table width="601" height="138" border="0">

                                      
                                      <tr>
                                        <td height="26">Session</td>
                                        <td><div align="center">:</div></td>
                                        <td><input name="sessi" type="text" id="sessi" value="<?php echo $row_test['sessi']; ?>" size="10" readonly="true" /></td>
                                      </tr>
                                      <tr>
                                        <td height="26">Year</td>
                                        <td><div align="center">:</div></td>
                                        <td><input name="year" type="text" id="year" value="<?php echo $row_test['year']; ?>" size="10" readonly="true" /></td>
                                      </tr>
								  <tr>
                                        <td width="92" height="26"><div align="left">Group</div></td>
                                        <td width="10"><div align="center">:</div></td>
                                        <td width="360"><input name="group" type="text" id="group" value="<?php echo $row_test['group']; ?>" size="10" readonly="true" /></td>
                                      </tr>
                                      <tr>
                                        <td height="22">Subject Code</td>
                                        <td><div align="center">:</div></td>
                                        <td><input name="s_code" type="text" id="s_code" value="<?php echo $row_test['s_code']; ?>" size="10" readonly="true" /></td>
                                      </tr>
                                      <tr>
                                        <td height="23">Title</td>
                                        <td><div align="center">:</div></td>
                                        <td><input name="s_title" type="text" id="s_title" size="80" value="<?php echo $row_Recordset2['s_title']; ?>" readonly="true" /></td>
                                      </tr>
                                    </table>
                                  </blockquote>
            </blockquote>
    </blockquote>
      </blockquote>

  <p> </p>
  <table width="609" height="54" border="0" align="center">
    <tr>
      <td width="60" height="28" scope="col"><span class="style15">Matric No.</span></td>
      <td width="48" scope="col"><span class="style15">CAM</span></td>
      <td width="48" scope="col"><div align="left" class="style15">
        <div align="center">Final Exam</div>
      </div>        </td>
      <td width="48" scope="col"><div align="left" class="style15">
        <div align="center">Total Score</div>
      </div></td>
      <td width="383" scope="col"><span class="style15">Grade</span></td>
      </tr>
  
      <?php do { ?>
        <tr>
          <td height="20" scope="col"><input name="matric_no[]" type="text" id="matric_no[]" value="<?php echo $row_test['matric_no']; ?>" size="10" readonly="true" /></td>
          <td scope="col"><input name="cam" type="int" id="cam" size="8" /></td>
          <td scope="col" ><input name="final_exam" type="int" id="final_exam" size="8" /></td>
          <td scope="col"><input name="total" type="int" id="total" size="8" onClick="calculate()"/></td>
          <td scope="col"><input name="grade" type="text" id="grade" size="8" onClick="gred()"/></td>
        </tr>
        <?php } while ($row_test = mysql_fetch_assoc($test)); ?>
</table>
  <p align="center"> </p>
  <table width="200" border="0" align="center">
    <tr>
      <th scope="col"><input name="save" type="submit" class="style13" id="save" value="Save" /></th>
      <th scope="col"><script type="text/javascript">
AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0','width','77','height','22','src','exmtry','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','bgcolor','#E4E7E6','scale','noborder','movie','exmtry' ); //end AC code
      </script>
        <noscript>
        <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="77" height="22">
          <param name="movie" value="exmtry.swf">
          <param name="quality" value="high">
          <param name="bgcolor" value="#E4E7E6">
          <param name="SCALE" value="noborder">
          <embed src="exmtry.swf" width="77" height="22" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" bgcolor="#E4E7E6" scale="noborder"></embed>
        </object>
        </noscript></th>
    </tr>
  </table>
  <div align="center"></div>
  <p align="center">  </p>
  <p> </p>
      <p align="center" class="style8"> </p>
</form> </td>
  </tr>

<tr>
  <td height="58" colspan="2"><table width="100%" height="39"  border="0" cellpadding="0" cellspacing="0">
        <tr>

          <td align="center" class="basestyle"><span class="style31 style10">© Copyright . All Rights Reserved. <a href="http://www.myfreetemplates.com" class="basestyle"></a></span></td>
        </tr>
      </table></td>
</tr>
</table>
</body>

<?php

mysql_free_result($test);

?>
</html>

Link to comment
Share on other sites

ook this is my php including html coding

 

To get assistance with JavaScript problems you should ONLY post the HTML that would be generated - not the PHP code. Your code is doing several database queries and I would not want to take the time & energy to try and reproduce your database to find a solution. Simply access the page from your browser and then extract the generated HTML.

 

If this is your PHP file:

<?php

echo "The current date is " . date('F j, Y');

?>

 

The HTML would be:

The current date is September 1, 2008

Link to comment
Share on other sites

<?php do { ?>
  
        <tr>
          <td height="39" scope="col"><input name="matric_no[]" type="text" id="matric_no" value="<?php echo $row_test['matric_no']; ?>" size="10"  readonly></td>
          <td scope="col"><input name="cam" type="int" id="cam" size="8" /></td>
          <td scope="col" ><input name="final_exam" type="int" id="final_exam" size="8" /></td>
          <td scope="col"><input name="total" type="int" id="total" size="8" onClick="calculate()" readonly/></td>
          <td scope="col"><input name="grade" type="text" id="grade" size="8" readonly/></td>
        </tr>
       

</table>

 

 

Link to comment
Share on other sites

OK, a few comments

 

1. The function is trying to update the total for each row whenever it is run - this is inefficient. You only need to update the total on the current row the user is working on.

 

2. Also, the function is only being run on an onclick of the total field. The user shouldn't need to click on the result field. You can simply do it on on onchange/onblur of the input fields.

 

3. I don't see a way to pass the function an index number such that you can use getElementsByName() in an efficinet manner. I would use an index in the id field when generated in the PHP.

 

4. It will help the usability to either remove the border from the readonly fields or use a div. This gives the user a visual cue that they cannot enter anything in them

 

Change the PHP script that creates the rows to this:

    <?php
        $indx = 1;
        while ($row_test = mysql_fetch_assoc($test)) {
    ?>
        <tr>
          <td height="20" scope="col"><input name="matric_no[]" type="text" id="matric_no[]" value="<?php echo $row_test['matric_no']; ?>" size="10" readonly="true" /></td>
          <td scope="col"><input name="cam" type="int" id="cam<?php echo $indx; ?>" size="8" onblur="calculate(this); /></td>
          <td scope="col" ><input name="final_exam" type="int" id="final_exam<?php echo $indx; ?>" size="8" onblur="calculate(this); /></td>
          <td scope="col"><input name="total" type="int" id="total<?php echo $indx; ?>" size="8" /></td>
          <td scope="col"><input name="grade" type="text" id="grade<?php echo $indx; ?>" size="8" /></td>
        </tr>
      <?php
          $indx++;
        }
    ?>

 

Change your function to this

function calculate(fldObj)
{
    var indx = fldObj.id.replace(/[^\d]/g, '');
    var fldName = fldObj.id.replace(/[^\D]/g, '');

    var camsObj  = document.getElementById('cam'+indx);
    var camsVal  = parseInt(camsObj.value);
    var finalObj = document.getElementById('final_exam'+indx);
    var finalVal = parseInt(finalObj.value);

    //Verify both number are positive integers
    if (fldName=='cam' && camsVal<0)
    {
        alert('You may not enter negative numbers!');
        camsObj.focus();
        camsObj.select();
        return false;
    }
    else if (fldName=='final_exam' && finalVal<0)
    {
        alert('You may not enter negative numbers!');
        finalObj.focus();
        finalObj.select();
        return false;
    }

    //Ensure both values are entered
    if (!camsObj.value || !finalObj.value)
    {
        return false;
    }

    //Create the total
    var totalVal = (camsVal + finalVal);

    //Validate total is not greater than 100
    if (totalVal>100)
    {
        alert('Total cannot be more than 100!');
        camsObj.select();
        camsObj.focus();
        return false;
    }

    //Populate the total
    document.getElementById('total'+indx).value = totalVal;    

    //Determine the grade
    var gradeVal;
         if (totalVal>=80) { gradeVal = 'A'; }
    else if (totalVal>=70) { gradeVal = 'B'; }
    else if (totalVal>=60) { gradeVal = 'C'; }
    else if (totalVal>=50) { gradeVal = 'D'; }
    else if (totalVal>=40) { gradeVal = 'E'; } 
    else                   { gradeVal = 'F'; }

    //Populate the grade
    document.getElementById('grade'+indx).value = gradeVal;
    return;
}

 

Just in case i have some typos, here is a complete working example:

<html>
<head>
<script>

function calculate(fldObj)
{
    var indx = fldObj.id.replace(/[^\d]/g, '');
    var fldName = fldObj.id.replace(/[^\D]/g, '');

    var camsObj  = document.getElementById('cam'+indx);
    var camsVal  = parseInt(camsObj.value);
    var finalObj = document.getElementById('final_exam'+indx);
    var finalVal = parseInt(finalObj.value);

    //Verify both number are positive integers
    if (fldName=='cam' && camsVal<0)
    {
        alert('You may not enter negative numbers!');
        camsObj.focus();
        camsObj.select();
        return false;
    }
    else if (fldName=='final_exam' && finalVal<0)
    {
        alert('You may not enter negative numbers!');
        finalObj.focus();
        finalObj.select();
        return false;
    }

    //Ensure both values are entered
    if (!camsObj.value || !finalObj.value)
    {
        return false;
    }

    //Create the total
    var totalVal = (camsVal + finalVal);

    //Validate total is not greater than 100
    if (totalVal>100)
    {
        alert('Total cannot be more than 100!');
        camsObj.select();
        camsObj.focus();
        return false;
    }

    //Populate the total
    document.getElementById('total'+indx).value = totalVal;    

    //Determine the grade
    var gradeVal;
         if (totalVal>=80) { gradeVal = 'A'; }
    else if (totalVal>=70) { gradeVal = 'B'; }
    else if (totalVal>=60) { gradeVal = 'C'; }
    else if (totalVal>=50) { gradeVal = 'D'; }
    else if (totalVal>=40) { gradeVal = 'E'; } 
    else                   { gradeVal = 'F'; }

    //Populate the grade
    document.getElementById('grade'+indx).value = gradeVal;
    return;
}

</script>
</head>

<body>

<table border=1>
        <tr>
          <td height="39" scope="col"><input name="matric_no[]" type="text" id="matric_no" value="50" size="10" readonly /></td>
          <td scope="col"><input name="cam" type="int" id="cam1" size="8" onBlur="calculate(this);" /></td>
          <td scope="col"><input name="final_exam" type="int" id="final_exam1" size="8" onBlur="calculate(this);" /></td>
          <td scope="col"><input name="total" type="int" id="total1" size="8" readonly /></td>
          <td scope="col"><input name="grade" type="text" id="grade1" size="8" readonly /></td>
        </tr>
        <tr>
          <td height="39" scope="col"><input name="matric_no[]" type="text" id="matric_no" value="50" size="10" readonly /></td>
          <td scope="col"><input name="cam" type="int" id="cam2" size="8" onBlur="calculate(this);" /></td>
          <td scope="col"><input name="final_exam" type="int" id="final_exam2" size="8" onBlur="calculate(this);" /></td>
          <td scope="col"><input name="total" type="int" id="total2" size="8" readonly /></td>
          <td scope="col"><input name="grade" type="text" id="grade2" size="8" readonly /></td>
        </tr>
</table>

</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.