Foros del Web » Programando para Internet » Javascript »

Calcular Promedio de 3 notas

Estas en el tema de Calcular Promedio de 3 notas en el foro de Javascript en Foros del Web. Tengo el siguiente script para calcular el promedio de 3 notas: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código PHP: Ver original < script > function prom ( ) { ...
  #1 (permalink)  
Antiguo 24/02/2013, 20:27
 
Fecha de Ingreso: enero-2013
Ubicación: Lima
Mensajes: 38
Antigüedad: 11 años, 3 meses
Puntos: 0
Calcular Promedio de 3 notas

Tengo el siguiente script para calcular el promedio de 3 notas:

Código PHP:
Ver original
  1. <script>
  2. function prom() {
  3. var num1 = parseInt(document.form1.n1.value);
  4. var num2 = parseInt(document.form1.n2.value);
  5. var num3 = parseInt(document.form1.n3.value);
  6. document.form1.pf.value=(num1+num2+num3)/3;
  7. }
  8. </script>

Luego en el formulario (form1), cargo el script mediante ONCHANGE como lo vemos a continuación, pero no consigo que se calcule el promedio. En este foro había visto este código y algunos comentaban que cuando escribían una nota en la text n1, automáticamente se promediaba, y cuando escribían en el text n2 de igual manera. Pero en mi caso no logro ningún resultado.

Código PHP:
Ver original
  1. <input name="n1[]" type="text" id="n1[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n1']; ?>" size="2" maxlength="2"/>
  2.         </label></td>
  3.         <td align="center"><label>
  4.           <input name="n2[]" type="text" id="n2[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n2']; ?>" size="2" maxlength="2"/>
  5.         </label></td>
  6.         <td align="center"><label>
  7.           <input name="n3[]" type="text" id="n3[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n3']; ?>" size="2" maxlength="2"/>
  8.         </label></td>
  9.         <td align="center"><label>
  10.           <input name="pf[]" type="text" id="pf[]" value="<?php echo $row_p['pf']; ?>" size="2" style="text-align: center" readonly="true" />

Lo estaba haciendo de otra manera sin Script. Directamente lo calculo desde el campo promedio (pf), pero lo malo es que tengo que darle doble clic al BUTTON para que me actualice los datos. Cuando le doy un clic al BUTTON, sólo calcula pero no envía los datos a la base de datos. Tengo que darle nuevamente otro clic para que recién actualice los registros. Si alguien sabe como realizar el cálculo y la actualización de datos con UN SÓLO CLIC, por favor ayuden ...

Última edición por tranquilo_8925; 24/02/2013 a las 20:32
  #2 (permalink)  
Antiguo 24/02/2013, 22:18
Avatar de ArturoGallegos
Moderador
 
Fecha de Ingreso: febrero-2008
Ubicación: Morelia, México
Mensajes: 6.774
Antigüedad: 16 años, 2 meses
Puntos: 1146
Respuesta: Calcular Promedio de 3 notas

n1 no es lo mismo que n1[] por ende no funciona tu script, también para que te podamos ayudar necesitas mostrarnos el código html generado, el código con php no nos sirve.
  #3 (permalink)  
Antiguo 25/02/2013, 05:48
 
Fecha de Ingreso: enero-2013
Ubicación: Lima
Mensajes: 38
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: Calcular Promedio de 3 notas

Muchas gracias ArturoGallegos por tu pronta respuesta. También lo hice poniéndole n1[], n2[] n3[], dentro del script, pero tampoco me funciona. Mejor pongo todo el código para que lo revises.

Código PHP:
Ver original
  1. <?php require_once('Connections/cnotas.php'); ?>
  2. <?php
  3. if (!function_exists("GetSQLValueString")) {
  4. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  5. {
  6.   $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  7.  
  8.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  9.  
  10.   switch ($theType) {
  11.     case "text":
  12.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  13.       break;    
  14.     case "long":
  15.     case "int":
  16.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  17.       break;
  18.     case "double":
  19.       $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
  20.       break;
  21.     case "date":
  22.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  23.       break;
  24.     case "defined":
  25.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  26.       break;
  27.   }
  28.   return $theValue;
  29. }
  30. }
  31.  
  32. $editFormAction = $_SERVER['PHP_SELF'];
  33. if (isset($_SERVER['QUERY_STRING'])) {
  34.   $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
  35. }
  36.  
  37. if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  38. foreach($_POST['cod_nota'] as $key =>$value) { // LÍNEA INCLUIDO
  39.   $updateSQL = sprintf("UPDATE ejemplo SET nombre=%s, n1=%s, n2=%s, n3=%s, pf=%s WHERE cod_nota=$value",
  40.                        GetSQLValueString($_POST['nombre'][$key], "text"),
  41.                        GetSQLValueString($_POST['n1'][$key], "text"),
  42.                        GetSQLValueString($_POST['n2'][$key], "text"),
  43.                        GetSQLValueString($_POST['n3'][$key], "text"),
  44.                        GetSQLValueString($_POST['pf'][$key], "text"),
  45.                        GetSQLValueString($_POST['cod_nota'][$key], "int"));
  46.  
  47.   mysql_select_db($database_cnotas, $cnotas);
  48.   $Result1 = mysql_query($updateSQL, $cnotas) or die(mysql_error());
  49. }
  50. } // } INCLUIDO
  51. $maxRows_p = 20;
  52. $pageNum_p = 0;
  53. if (isset($_GET['pageNum_p'])) {
  54.   $pageNum_p = $_GET['pageNum_p'];
  55. }
  56. $startRow_p = $pageNum_p * $maxRows_p;
  57.  
  58. mysql_select_db($database_cnotas, $cnotas);
  59. $query_p = "SELECT * FROM ejemplo ORDER BY nombre ASC";
  60. $query_limit_p = sprintf("%s LIMIT %d, %d", $query_p, $startRow_p, $maxRows_p);
  61. $p = mysql_query($query_limit_p, $cnotas) or die(mysql_error());
  62. $row_p = mysql_fetch_assoc($p);
  63.  
  64. if (isset($_GET['totalRows_p'])) {
  65.   $totalRows_p = $_GET['totalRows_p'];
  66. } else {
  67.   $all_p = mysql_query($query_p);
  68.   $totalRows_p = mysql_num_rows($all_p);
  69. }
  70. $totalPages_p = ceil($totalRows_p/$maxRows_p)-1;
  71. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  72. <html xmlns="http://www.w3.org/1999/xhtml">
  73. <head>
  74. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  75. <title>Promedios</title>
  76.  
  77.  
  78. <script>
  79. function prom() {
  80. var num1 = parseInt(document.form1.n1.value);
  81. var num2 = parseInt(document.form1.n2.value);
  82. var num3 = parseInt(document.form1.n3.value);
  83. document.form1.pf.value=(num1+num2+num3)/3;
  84. }
  85. </script>
  86.  
  87.  
  88.  
  89. <style type="text/css">
  90. <!--
  91. .Estilo1 {
  92.     font-size: 22px;
  93.     font-weight: bold;
  94.     font-style: italic;
  95.     color: #FF0000;
  96. }
  97. -->
  98. </style>
  99. </head>
  100.  
  101. <body>
  102. <p align="center" class="Estilo1">Actualizar Promedios</p>
  103. <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>">
  104.   <table border="1" align="center" cellpadding="1" cellspacing="0">
  105.     <tr align="center">
  106.       <td>C&oacute;digo</td>
  107.       <td>Apellidos y Apellidos</td>
  108.       <td>N1</td>
  109.       <td>N2</td>
  110.       <td>N3</td>
  111.       <td>Prom</td>
  112.     </tr>
  113.     <?php do { ?>
  114.       <tr>
  115.         <td align="center"><label>
  116.           <input name="cod_nota[]" type="text" id="cod_nota[]" value="<?php echo $row_p['cod_nota']; ?>" size="4" style="text-align: center" readonly="true" />
  117.         </label></td>
  118.         <td><label>
  119.           <input name="nombre[]" type="text" id="nombre[]" value="<?php echo $row_p['nombre']; ?>" size="45" readonly="true" />
  120.         </label></td>
  121.         <td align="center"><label>
  122.           <input name="n1[]" type="text" id="n1[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n1']; ?>" size="2" maxlength="2"/>
  123.         </label></td>
  124.         <td align="center"><label>
  125.           <input name="n2[]" type="text" id="n2[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n2']; ?>" size="2" maxlength="2"/>
  126.         </label></td>
  127.         <td align="center"><label>
  128.           <input name="n3[]" type="text" id="n3[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n3']; ?>" size="2" maxlength="2"/>
  129.         </label></td>
  130.         <td align="center"><label>
  131.           <input name="pf[]" type="text" id="pf[]" value="<?php echo $row_p['pf']; ?>" size="2" style="text-align: center" readonly="true" />
  132.         </label></td>
  133.       </tr>
  134.       <?php } while ($row_p = mysql_fetch_assoc($p)); ?>
  135.   </table>
  136.   <table width="200" border="0" align="center" cellpadding="0" cellspacing="0">
  137.     <tr>
  138.       <td>&nbsp;</td>
  139.     </tr>
  140.     <tr>
  141.       <td align="center"><label>
  142.         <input type="submit" name="button" id="button" value="Guardar Cambios" />
  143.       </label></td>
  144.     </tr>
  145.   </table>
  146.   <input type="hidden" name="MM_update" value="form1" />
  147. </form>
  148. </body>
  149. </html>
  150. <?php
  151. ?>

Ese es todo el código de mi página. Revísalo y me dices donde estoy fallando ... Muchas gracias de veras por tu ayuda ...
  #4 (permalink)  
Antiguo 25/02/2013, 07:25
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Calcular Promedio de 3 notas

Cita:
Iniciado por tranquilo_8925 Ver Mensaje
Muchas gracias ArturoGallegos por tu pronta respuesta. También lo hice poniéndole n1[], n2[] n3[], dentro del script, pero tampoco me funciona. Mejor pongo todo el código para que lo revises.

Código PHP:
Ver original
  1. <?php require_once('Connections/cnotas.php'); ?>
  2. <?php
  3. if (!function_exists("GetSQLValueString")) {
  4. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  5. {
  6.   $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  7.  
  8.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  9.  
  10.   switch ($theType) {
  11.     case "text":
  12.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  13.       break;    
  14.     case "long":
  15.     case "int":
  16.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  17.       break;
  18.     case "double":
  19.       $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
  20.       break;
  21.     case "date":
  22.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  23.       break;
  24.     case "defined":
  25.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  26.       break;
  27.   }
  28.   return $theValue;
  29. }
  30. }
  31.  
  32. $editFormAction = $_SERVER['PHP_SELF'];
  33. if (isset($_SERVER['QUERY_STRING'])) {
  34.   $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
  35. }
  36.  
  37. if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  38. foreach($_POST['cod_nota'] as $key =>$value) { // LÍNEA INCLUIDO
  39.   $updateSQL = sprintf("UPDATE ejemplo SET nombre=%s, n1=%s, n2=%s, n3=%s, pf=%s WHERE cod_nota=$value",
  40.                        GetSQLValueString($_POST['nombre'][$key], "text"),
  41.                        GetSQLValueString($_POST['n1'][$key], "text"),
  42.                        GetSQLValueString($_POST['n2'][$key], "text"),
  43.                        GetSQLValueString($_POST['n3'][$key], "text"),
  44.                        GetSQLValueString($_POST['pf'][$key], "text"),
  45.                        GetSQLValueString($_POST['cod_nota'][$key], "int"));
  46.  
  47.   mysql_select_db($database_cnotas, $cnotas);
  48.   $Result1 = mysql_query($updateSQL, $cnotas) or die(mysql_error());
  49. }
  50. } // } INCLUIDO
  51. $maxRows_p = 20;
  52. $pageNum_p = 0;
  53. if (isset($_GET['pageNum_p'])) {
  54.   $pageNum_p = $_GET['pageNum_p'];
  55. }
  56. $startRow_p = $pageNum_p * $maxRows_p;
  57.  
  58. mysql_select_db($database_cnotas, $cnotas);
  59. $query_p = "SELECT * FROM ejemplo ORDER BY nombre ASC";
  60. $query_limit_p = sprintf("%s LIMIT %d, %d", $query_p, $startRow_p, $maxRows_p);
  61. $p = mysql_query($query_limit_p, $cnotas) or die(mysql_error());
  62. $row_p = mysql_fetch_assoc($p);
  63.  
  64. if (isset($_GET['totalRows_p'])) {
  65.   $totalRows_p = $_GET['totalRows_p'];
  66. } else {
  67.   $all_p = mysql_query($query_p);
  68.   $totalRows_p = mysql_num_rows($all_p);
  69. }
  70. $totalPages_p = ceil($totalRows_p/$maxRows_p)-1;
  71. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  72. <html xmlns="http://www.w3.org/1999/xhtml">
  73. <head>
  74. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  75. <title>Promedios</title>
  76.  
  77.  
  78. <script>
  79. function prom() {
  80. var num1 = parseInt(document.form1.n1.value);
  81. var num2 = parseInt(document.form1.n2.value);
  82. var num3 = parseInt(document.form1.n3.value);
  83. document.form1.pf.value=(num1+num2+num3)/3;
  84. }
  85. </script>
  86.  
  87.  
  88.  
  89. <style type="text/css">
  90. <!--
  91. .Estilo1 {
  92.     font-size: 22px;
  93.     font-weight: bold;
  94.     font-style: italic;
  95.     color: #FF0000;
  96. }
  97. -->
  98. </style>
  99. </head>
  100.  
  101. <body>
  102. <p align="center" class="Estilo1">Actualizar Promedios</p>
  103. <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>">
  104.   <table border="1" align="center" cellpadding="1" cellspacing="0">
  105.     <tr align="center">
  106.       <td>C&oacute;digo</td>
  107.       <td>Apellidos y Apellidos</td>
  108.       <td>N1</td>
  109.       <td>N2</td>
  110.       <td>N3</td>
  111.       <td>Prom</td>
  112.     </tr>
  113.     <?php do { ?>
  114.       <tr>
  115.         <td align="center"><label>
  116.           <input name="cod_nota[]" type="text" id="cod_nota[]" value="<?php echo $row_p['cod_nota']; ?>" size="4" style="text-align: center" readonly="true" />
  117.         </label></td>
  118.         <td><label>
  119.           <input name="nombre[]" type="text" id="nombre[]" value="<?php echo $row_p['nombre']; ?>" size="45" readonly="true" />
  120.         </label></td>
  121.         <td align="center"><label>
  122.           <input name="n1[]" type="text" id="n1[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n1']; ?>" size="2" maxlength="2"/>
  123.         </label></td>
  124.         <td align="center"><label>
  125.           <input name="n2[]" type="text" id="n2[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n2']; ?>" size="2" maxlength="2"/>
  126.         </label></td>
  127.         <td align="center"><label>
  128.           <input name="n3[]" type="text" id="n3[]" style="text-align: center" onchange="prom()" value="<?php echo $row_p['n3']; ?>" size="2" maxlength="2"/>
  129.         </label></td>
  130.         <td align="center"><label>
  131.           <input name="pf[]" type="text" id="pf[]" value="<?php echo $row_p['pf']; ?>" size="2" style="text-align: center" readonly="true" />
  132.         </label></td>
  133.       </tr>
  134.       <?php } while ($row_p = mysql_fetch_assoc($p)); ?>
  135.   </table>
  136.   <table width="200" border="0" align="center" cellpadding="0" cellspacing="0">
  137.     <tr>
  138.       <td>&nbsp;</td>
  139.     </tr>
  140.     <tr>
  141.       <td align="center"><label>
  142.         <input type="submit" name="button" id="button" value="Guardar Cambios" />
  143.       </label></td>
  144.     </tr>
  145.   </table>
  146.   <input type="hidden" name="MM_update" value="form1" />
  147. </form>
  148. </body>
  149. </html>
  150. <?php
  151. ?>

Ese es todo el código de mi página. Revísalo y me dices donde estoy fallando ... Muchas gracias de veras por tu ayuda ...
tenés que pasar el html generado no el php

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #5 (permalink)  
Antiguo 25/02/2013, 07:37
 
Fecha de Ingreso: enero-2013
Ubicación: Lima
Mensajes: 38
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: Calcular Promedio de 3 notas

Gracias EMPREAR por tu respuesta, pero ese es todo el código, revísalo y te darás cuenta. Todo lo genero en una sola página ...

Gracias ...
  #6 (permalink)  
Antiguo 25/02/2013, 07:51
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Calcular Promedio de 3 notas

Cita:
Iniciado por tranquilo_8925 Ver Mensaje
Gracias EMPREAR por tu respuesta, pero ese es todo el código, revísalo y te darás cuenta. Todo lo genero en una sola página ...

Gracias ...
No colega, vos tenés que entregar el HTML generado por tu php, este es el foro de Javascript, o supones que voy a crear una base de datos y generar dinamicamente una tabla con un form para verificar tu ejemplo

por si te sirve
Código HTML:
Ver original
  1. <!DOCTYPE html>
  2. <html lang="es-ar">
  3. <meta charset="utf-8" />
  4. <title>Html5</title>
  5. function p(){
  6. var num1 = parseFloat(document.getElementById('n1').value);
  7. var num2 =parseFloat(document.getElementById('n2').value);
  8. var num3 = parseFloat(document.getElementById('n3').value);
  9. var pro =(num1+num2+num3)/3;
  10. if(!isNaN(pro))
  11. document.getElementById('promedio').innerHTML = pro.toFixed(2);
  12. }
  13. </head>
  14. <form action="#">
  15.     <input type="text" value="" id="n1" onkeyup="p();">
  16.     <input type="text" value="" id="n2" onkeyup="p();">
  17.     <input type="text" value="" id="n3" onkeyup="p();">
  18. </form>
  19. <div id="promedio">
  20. </div>
  21. </body>
  22. </html>
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.

Etiquetas: formulario, notas, php, promedio, registro
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:44.