Foros del Web » Programando para Internet » Javascript »

Sumatoria de campo en formulario HTML con funciones JS

Estas en el tema de Sumatoria de campo en formulario HTML con funciones JS en el foro de Javascript en Foros del Web. Esperamos que alguno de ustedes, expertos en el tema nos puedan ayudar con un problema que tenemos el cual consiste en: Estamos tratando que la ...
  #1 (permalink)  
Antiguo 18/06/2004, 10:02
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
Sumatoria de campo en formulario HTML con funciones JS

Esperamos que alguno de ustedes, expertos en el tema nos puedan ayudar con un problema que tenemos el cual consiste en:

Estamos tratando que la captura de informacion de unos campos sea dinamica de acuerdo a que en un campo inicial digan cuantos productos desean. Una vez se tenga esa informacion se despliegue el numero de campos para capturar el codigo y valor de cada uno de los articulos sin que se cambie de documento o de pagina (por la instruccion document.write que nos crae otra forma) e ir mostrando la sumatoria de estos valores en otro campo de total (si se pudiera sin necesidad de un boton de sumatoria) par ir verificando la suma.

Nosotros estamos haciendo el siguiente script, pero nos arroja un error en la sentencia donde llama la funcion de sumar1 por que necesitamos enviar el valor del indice para que lo almacene en otro vector y depues de alli sacar la suma ( que no es lo ideal).

Agradecemos mucho sus aportes, ya que llevamos mucho tiempo con este problemita que nos esta llevando a la locura y a no querer a JAVASCRIPT.

URGENTE.......S.O.S


<html>
<head>

<script language="javascript">

var resul = 0;
var valores = new Array(0);
var con = 0;
var ind = 0;
var valorind = 0;
var valor = 0;



function sumar1(valor)
{
var res1=valor;
resul= resul + parseInt(res1) ;
document.getElementById('tot').value=resul;
}
function mostrar(contador)
{
var cont=parseInt(contador);

for (con=1;con<=cont;con++)
{
document.write("<input type=\"text\" name=\"vrcife[]\" id=\"vrcife1\" size=\"10\" maxlength=\"10\" onkeyup=\"if(isNaN(this.value))alert('El valor NO ES NUMERICO')\" onchange=\"sumar1(this.value)\" /> <br>");
valorind = parseInt(document.getElementById('vrcife1').value) ;
valores[con]= valorind;
}
}



</script>

</head>
<body>
<form name="forma10" method="POST" action="seccion5.php" enctype="multipart/form-data">
<table width="100%" border="1" cellspacing="1" cellpadding="1">

<td>Cantidad de Productos</td>
<td>
<form name="canex" method="POST" action="seccion5.php">
<input type="text" id="can" name="canex" size="2" maxlength="2" class="cajita" onkeyup="if(isNaN(this.value))alert('El valor NO es NUMERICO')" onChange="mostrar(this.value)" />
</form>
</td>
<tr>
<td colspan="7">Valor total:</td>
<td><input name="tot" id="tot" type="text" size="12" maxlength="12" value="0" disabled /></td>
</tr>
</form>
</body>
</html>



  #2 (permalink)  
Antiguo 22/06/2004, 08:28
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
Hola usuarios del Foro, no se si es que no me he hecho entender con mi pregunta o es que realmente lo que estoy tratando de hacer sea imposible en Javascript. Por favor que alguien me responda para ayudar a salir de este dilema.

Muchas gracias, por su valiosos aportes
  #3 (permalink)  
Antiguo 22/06/2004, 11:01
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 2 meses
Puntos: 772
Hola, pjcaro.

A veces me resulta más fácil hacer un código nuevo que intentar cambiar otro. Aquí tienes esto, espero que te ayude:
Código HTML:
<html>
<head>
<script>
var num=0;
function aceptar() {
	num=document.getElementById('numero').value;
	frm=document.forms[0];
	for(i=0;i<num;i++) {
		txt=document.createTextNode('Artículo '+i);
		frm.appendChild(txt);
		inp=document.createElement('input');
		inp.id='ar'+i;
		inp.value='0';
		inp.onkeyup=function() {
			var tot=0;
			for(i=0;i<num;i++)
				tot+=parseInt(document.getElementById('ar'+i).value);
			document.getElementById('total').value=tot;
		}
		frm.appendChild(inp);
		frm.appendChild(document.createElement('br'));
	}
}
</script>
</head>

<body>
<form>
Nº Artículos:&nbsp;<input type="text" id="numero" />
<input type="button" value="Aceptar" onclick="aceptar()" />
<br />
Total:&nbsp;<input type="text" id="total" /><br />
</form>
</body>
</html> 
Saludos,
  #4 (permalink)  
Antiguo 22/06/2004, 15:12
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
JavierB, muchas gracias por su ayuda, pero ahora tenemos otro pequeño inconveniente : el campo de captura debe quedar en otra linea mas otros campos. Con la rutina dada se expande el campo inmediatamente despues en la misma td del campo de captura y los titulos salen debajo de donde se deben pedir los datos (cantidad, valor, valorcif, valorplanta).
Mil gracias si nos puede ayudar.
Sera que se necesita crear una nueva fila dentro del formulario, Pero en que parte se puede colocar?
el scripr es el siguiente:

<html>
<head>

<link href="estiloforma10.css" rel="stylesheet" type="text/css">

<script language="javascript">



var num=0;
function mostrar()
{
num=document.getElementById('canex').value;
frm=document.forms[0];
frm.appendChild(document.createElement('/td'));
frm.appendChild(document.createElement('table'));
frm.appendChild(document.createElement('tr'));
frm.appendChild(document.createElement('td'));
for(i=0;i<num;i++)
{
txt=document.createTextNode('Artículo '+i);
frm.appendChild(txt);
inp=document.createElement('input');
inp.id='ar'+i;
inp.value='0';
inp.onkeyup=function()
{
var tot=0;
for(i=0;i<num;i++)
tot+=parseInt(document.getElementById('ar'+i).valu e);
document.getElementById('total').value=tot;
}
frm.appendChild(inp);
frm.appendChild(document.createElement('br'));
}
}
</script>




</script>

</head>
<body>
<form name="forma10" method="POST" action="seccion5.php" enctype="multipart/form-data">
<table width="100%" border="1" cellspacing="1" cellpadding="1">

<td>Cantidad de Productos </td>
<td>
<form name="canex" method="POST" action="seccion5b.php">
<!-- <input type="text" id="can" name="canex" size="2" maxlength="2" class="cajita" onkeyup="if(isNaN(this.value))alert('El valor NO es NUMERICO')" onChange="mostrar(this.value)" />
-->
<input type="text" id="canex" name="canex" size="2" maxlength="2" class="cajita" onkeyup="if(isNaN(this.value))alert('El valor NO es NUMERICO')" onChange="mostrar()" />
</form>
</td>
<div id="materex">
<table width="100%" border="1" cellspacing="1" cellpadding="1">
<tr>
<td rowspan="2">No</td>
<td>Descripción</td>
<td>Subpartida</td>
<td>Pais</td>
<td>Pais</td>
<td>Unidad de</td>
<td>Cantidad</td>
<td>Valor CIF</td>
<td>Valor Planta</td>
</tr>
<tr>
<td>Nombre Tecnico</td>
<td>&nbsp;</td>
<td>Origen</td>
<td>Procedencia</td>
<td>Medida</td>
<td colspan="3">Por Unidad Comercial de Producto</td>
</tr>


<tr>
<td colspan="7">Valor total:</td>
<td><input name="total" id="total" type="text" size="12" maxlength="12" value="0" disabled /></td>
</tr>
</table>
</table>

</div>
</form>
</body>
</html>
  #5 (permalink)  
Antiguo 23/06/2004, 08:51
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
Nosotros no somos muy expertos en Javascript y creemos que la solucion puede ser muy sencilla, o sera que se debe manejar de otra forma?

De antemano gracias por sus aportes.
  #6 (permalink)  
Antiguo 23/06/2004, 11:16
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 2 meses
Puntos: 772
Hola de nuevo.

No entiendo bien que es lo que quieres hacer. ¿Quieres crear una fila de tabla por cada control nuevo?

Además veo que has puesto un formulario dentro de otro formulario. No estoy seguro, pero me parece que eso no se puede hacer.

Saludos,
  #7 (permalink)  
Antiguo 23/06/2004, 13:24
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
hOLA JAVIERB, Así esta quedando según el script que te enviamos. Deja los valores a capturar dentro del TD o celda donde capturamos en número de ítems a capturar. Es decir no se sale del TD, para seguir el curso de la forma se nos queda alli la secuencia de la froma y donde debe sacar las columnas de captura, abajo del área de los titulos que referi ayer (Valor Cif, Valor Planta, Cantidad), no sigue la secuencia como si uno tuviera la froma toda en HTML. Me entiendes.

Te anexo el código del scripT de php, que tenemos implementado. Para haber si lo puedes correR como un archivo .php, y veAs como deseamos. (trate de pegar aqui una imgaen pero no la une), SI TE SACA ERRORES ES POR QUE ESTA ES UAN PORCION DE UN FORMULARIO BIEN GRANDE, PERO AL DECIR QUE NO SE CORRIGE TE SIGUE HASTA QUE PUEDAS VER EL FORMULARIO.

MIL GRACIAS POR TUS APORTES.

<html>
<head>

<link href="estiloforma10.css" rel="stylesheet" type="text/css">
<?php
$resul = 0;
function sumaphp($valor)
{
echo " Valor a sumar '$valor' <br>\n";
$res1=valor;
$resul= $resul + $res1;
$tot5111= $resul;
}

?>


<script language="javascript">
var resul = 0;
var resul2 = 0;
var resul3 = 0;
var resul61 = 0;
function traer(valor)
{
var res61 = valor;
resul61 = parseInt(res61);
document.getElementById('vr71').value=resul61;
}

function sumar1(valor)
{
var res1=valor;
resul= resul + parseInt(res1) ;
document.getElementById('tot5111').value=resul;
}

function sumar2(valor)
{
var res2=valor;
resul2 = resul2 + parseInt(res2) ;
document.getElementById('tot5112').value=resul2;
}
function sumar3(valor)
{
var res3=valor;
resul3= resul3 + parseInt(res3) ;
document.getElementById('tot611').value=resul3;
document.getElementById('vr71').value=resul3;
}

function NumberFormat(num, numDec, decSep, thousandSep)
{
var arg;
var Dec;
Dec = Math.pow(10, numDec);
if (typeof(num) == 'undefined') return;
if (typeof(decSep) == 'undefined') decSep = ',';
if (typeof(thousandSep) == 'undefined') thousandSep = '.';
if (thousandSep == '.')
arg=/./g;
else
if (thousandSep == ',') arg=/,/g;
if (typeof(arg) != 'undefined') num = num.toString().replace(arg,'');
num = num.toString().replace(/,/g, '.');
if (isNaN(num)) num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Dec + 0.50000000001);
cents = num % Dec;
num = Math.floor(num/Dec).toString();
if (cents < (Dec / 10)) cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + thousandSep + num.substring(num.length - (4 * i + 3));
if (Dec == 1)
return (((sign)? '': '-') + num);
else
return (((sign)? '': '-') + num + decSep + cents);
}

function EvaluateText(cadena, obj)
{
opc = false;
if (cadena == "%d")
if (event.keyCode > 47 && event.keyCode < 58)
opc = true;
if (cadena == "%f"){
if (event.keyCode > 47 && event.keyCode < 58)
opc = true;
if (obj.value.search("[.*]") == -1 && obj.value.length != 0)
if (event.keyCode == 46)
opc = true;
}
if(opc == false)
event.returnValue = false;
}

</script>

</head>
<body>
<form name="forma10" method="POST" action="pruebita.php" enctype="multipart/form-data">

<div id="canex">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr class="row1"><td colspan="9">5. MATERIALES EXTRANJEROS IMPORTADOS DIRECTAMENTE O ADQUIRIDOS EN EL MERCADO NACIONAL</td></tr>
<tr class="row2">
<td>Cantidad de Productos Extranjeros</td>
<td>
<form name="canex" method="POST" action="pruebita.php">
<input type="text" name="canex" size="2" maxlength="2" class="cajita" />
<input type="hidden" name="cannal" value="<?php echo $cannal;?>" />
<input type="submit" name="enviarex" value="Continuar" class="boton"/>
</form>
</td>
</tr>
</table>
</div>
<?php
if( $canex!=0)
{
?>
<div id="materex">
<table width="100%" border="1" cellspacing="1" cellpadding="1">
<tr>
<td rowspan="2">No</td>
<td>Descripción</td>
<td>Subpartida</td>
<td>Pais</td>
<td>Pais</td>
<td>Unidad de</td>
<td>Cantidad</td>
<td>Valor CIF</td>
<td>Valor Planta</td>
</tr>
<tr>
<td>Nombre Tecnico</td>
<td>&nbsp;</td>
<td>Origen</td>
<td>Procedencia</td>
<td>Medida</td>
<td colspan="3">Por Unidad Comercial de Producto</td>
</tr>
<?php
for($i=1;$i<=$canex;$i++)
{
?>
<tr>
<td><?php echo $i;?></td>
<td><input name="desmate[]" type="text" size="30" maxlength="30" /></td>
<td><input name="subpare[]" type="text" size="10" maxlength="10" /></td>
<!-- <td><input name="paisore[]" type="text" size="10" maxlength="10" /></td> -->
<td>
<select name="idpais" class="cajita">
<?php
$fich=file("paises.txt");
$j=0;
while ($fich[$j])
{
$campo=explode(";",$fich[$j]);
$idpais=$campo[0];
$pais=$campo[1];
?>
<option value="<?php echo $idpais;?>"><?php echo $pais;?></option>
<?php
$j++;
}
?>
</select>
</td>
<td><input name="paisproe[]" type="text" size="10" maxlength="10" /></td>
<td><input name="unmede[]" type="text" size="3" maxlength="3" /></td>
<td><input name="cantidade[]" type="text" size="10" maxlength="10"
value="0" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')" />
</td>
<td><input name="vrcife[]" type="text" size="10" maxlength="10" onChange="<?php sumaphp(this.value);?>"
value="0" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')"/>
</td>
<td><input name="vrplantae[]" type="text" size="10" maxlength="10" onChange="sumar2(this.value)"
value="0" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')" />
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="7">5.11 Valor total por unidad de producto(Col$):</td>

<td><input name="tot5111" id="tot5111" type="text" size="12" maxlength="12" value="<?php $resul ?>" disabled
value="0" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')" />
</td>
<td><input name="tot5112" id="tot5112" type="text" size="12" maxlength="12" value="0" disabled
value="0" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')" />
</td>
</tr>
</table>
</div>
<?php
}
?>

</form>
</body>
</html>
  #8 (permalink)  
Antiguo 24/06/2004, 08:01
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
Hola JavierB.

Espero que haya visto nuestro ultimo mensaje (mensaje #6), y si tiene alguna duda nos pregunta, haber si nos puede seguir ayudando. No se si decirle Buenos días o buenas tardes, aqui son las 9:00 a.m. no se por alla. Quedamos pendientes y muchas gracias.
  #9 (permalink)  
Antiguo 24/06/2004, 11:04
 
Fecha de Ingreso: agosto-2002
Mensajes: 88
Antigüedad: 21 años, 8 meses
Puntos: 1
Hola a todos, nosotros aca seguimos desesperados buscando una solucion a nuestro problema con Javascript.
Esperamos alguna ayuda de ustedes los expertos en la materia.

AYUDA POR FAVOR!!!!!!
URGENTE.
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 02:17.