Ver Mensaje Individual
  #1 (permalink)  
Antiguo 10/09/2010, 06:50
marco_sa
 
Fecha de Ingreso: diciembre-2007
Mensajes: 113
Antigüedad: 16 años, 4 meses
Puntos: 0
Multiplicar datos dinamicos con JavaScript

Hola a todos/as

Despues de la pelea de estos dias con el onchange, que por fin funciona perfectamente, me veo en un dilema o mas bien un problema, os explico tengo 4 celdas en una tabla, estas se van creando segun las necesito pulsando añadir o borrar, bien esta conformada asi:

combo con descripcion, lo selecciono y me imprime en la siguiente celda en un input el precio unitario, la tercera celda es otro combo unidades de producto, y la cuarta celda es la multiplicacion del combo unidades por el precio unitario, bien si fuera una tabla no dinamica lo tendria resuelto, mi problema viene en como hacer los eventos para que se realize la dichosa multiplicacion.

La funcion encargada de hacer la dichos multiplicacion es calculaTotalProducto1

Os pongo el codigo que tengo JavaScript

Código:
 

// Funcion que añade filas a una tabla dinamicamente
function addRowToTable()
{
  var tbl = document.getElementById('tabla');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
   
  // Combo nombre producto
  var celdaComboNombreProducto = row.insertCell(0);
  var sel = document.createElement('select');
  sel.name = 'nombre_producto' + iteration;
  sel.id = 'id_producto' + iteration;
  sel.options[0] = new Option('Seleccion', '0');
   
  // Cargamos desde mysql el combobox
  <?Php
$sqltarifa=mysql_query("select * from productos");
while ($ftarifa=mysql_fetch_array($sqltarifa)){
print "sel.options['".$ftarifa[0]."']= new Option ('".$ftarifa[3]."','".$ftarifa[7]."');";
}
mysql_free_result($sqltarifa);
?>
  sel.onchange = function(){muestraPrecioProducto(this.value,this.id);}
  celdaComboNombreProducto.appendChild(sel);

// input precio producto
  var celdaPrecioProducto = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'precio_producto' + iteration;
  el.id = 'id_producto' + iteration + '_precio';
  el.size = 8;
  celdaPrecioProducto.appendChild(el);
  
  // unidades de producto
  var comboUnidadProducto = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'unidades_producto' + iteration;
  sel.id = 'id_unidades' + iteration;
  sel.options[0] = new Option('Cantidad', '0');
  sel.options[1] = new Option('1', '1');
  sel.options[2] = new Option('2', '2');
  sel.options[3] = new Option('3', '3');
  sel.options[4] = new Option('4', '4');
  sel.options[5] = new Option('5', '5');
  sel.options[6] = new Option('6', '6');
  sel.onchange = function(){calculaTotalProducto1(this.id,this.value);}
  comboUnidadProducto.appendChild(sel);
  
  // Total producto
  var celdaTotalProducto = row.insertCell(3);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'total_producto' + iteration; 
  el.id = 'id_producto' + iteration + '_total';
  el.size = 8;
  celdaTotalProducto.appendChild(el);
}

function calculaTotalProducto1(valor, id) {
// Cogemos el valor del select 
var unidades = document.getElementById(valor).options[document.getElementById(valor).selectedIndex].value;
 //Aqui intento conseguir componer para traerme el valor de id_productonumero_total
var precio = document.getElementById('id_producto' +id+ '_precio').value;
 //Aqui generamos multiplicacion
var multiplica = parseFloat(unidades)*parseFloat(precio);


//Aqui imprimimos en el input el total
document.getElementById('id_producto' +id+ '_total').value= multiplica;
//document.getElementById(id+ '_precio').value = valor;
}
Codigo HTML

Código HTML:
<form action="tableaddrow_nw.html" method="get" name="frm1" id="frm2">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
</p>
<p>

<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tabla">
  <tr>
   <th colspan="3">Tabla Ejemplo</th>
  </tr>
  <tr>


    <td><?
$sqltarifa=mysql_query("select * from productos");

echo '<select name="nombre_producto1" id="id_producto1" onChange="muestraPrecioProducto1()">';
echo '<option value="0">Seleccione </option>';
while ($ftarifa=mysql_fetch_array($sqltarifa)){
echo '<option value="' . $ftarifa[7] . '" >' . $ftarifa[3] . '</option>';
}
echo '</select>';

mysql_free_result($sqltarifa);
?>

    </td>
        <td><input type="text" name="precio_producto1" id="id_producto1_precio" size="8" value="0"/></td>
        <td>
    <select name="unidades_producto1" id="id_unidades1" onchange="calculaTotalProducto()">
          <option value="0" selected>Cantidad</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
    </select>
    </td> 
        <td><input type="text" name="producto1_total" id="id_producto1_total" size="8" value="0" /></td>
  </tr>
</table> 

Me devuelve este error "document.getElementById("id_producto" + id + "_precio") is null" y no hay manera de pasar el id de la fila para coger el valor y operar con el.

Haber si alguien me puede hechar una mano y decorme que hago mal.

Muchas gracias por vuestro tiempo.

Saludos