-1

tengo este código donde simulo un creador de factura. también tiene un boton donde se añade mas filas para poder añadirle elementos naturales a una factura. Los campos total_gr y total_cost deben sumare y mostrar el resultado en grand_total. El problema radica cuando añado el código que está arriba del div , div class="container" algún elemento del código no me está permitiendo sumar las clases, pero, cuando quito el código arriba de la clase div class="container" las clases total_gr y total_cost si muestran el resultado en el id id="grand_total"

    function addRow(tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        if (rowCount < 10) {
            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;
            row.id = 'row_' + rowCount;
            for (var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.outerHTML = table.rows[0].cells[i].outerHTML;
            }
            var listitems = row.getElementsByTagName("input")
            for (i = 0; i < listitems.length - 1; i++) {
                listitems[i].setAttribute("oninput", "calculate('" +
                    row.id + "')");
            }
            listitems[listitems.length - 1].setAttribute("onclick", "removeRow('dataTable', " + row.id.replace("row_", "") + ")");
        } else {
            alert("Maximum 10.");

        }
    }


    function removeRow(tableID, index) {
        //Removing the row
        var table = document.getElementById(tableID);
        table.deleteRow(index);
        //Modifying the ids of subsequent rows
        var rowCount = table.rows.length;
        for (var i = index; i < rowCount; i++) {
            table.rows[i].id = "row_" + i;
            table.rows[i].getElementsByClassName("remove")[0].setAttribute("onclick", "removeRow('dataTable', " + i + ");");
        }
        //Handling the counts
        grandtotal();
    }


    function calculate(elementID) {
        var mainRow = document.getElementById(elementID);
        var myBox1 = mainRow.querySelectorAll('[class=qty]')[0].value;
        var myBox2 = mainRow.querySelectorAll('[class=cost]')[0].value;
		var myBox3 = mainRow.querySelectorAll('[class=gr]')[0].value;
        var total = mainRow.querySelectorAll('[class=subtotal]')[0];
        var myResult1 = myBox1 * (myBox2 + myBox3);
		
        total.value = myResult1;
		
		
		
		
		

        grandtotal();
	  
    }

    function grandtotal(){

        //calculation script
        var $form = $('#add_service'),
            $sumDisplay = $('#grand_total');

        var $summands = $form.find('.subtotal');
        var sum = 0;
        $summands.each(function ()
        {
            var value = Number($(this).val());
            if (!isNaN(value)) sum += value;
        });

        $sumDisplay.val(sum);
    }
	
	
	function sumargr() {

  var total = 0; //inicimos una variable para concatenarle la suma de los inputs

  $(".gr").each(function() { //recorremos el arreglo 

    if (isNaN(parseFloat($(this).val()))) { //con la propiedad this obtenemos el valor del input donde estemos escribiendo y validamos que no sea un número
    //si no lo es agregamos un 0

      total += 0;

    } else {
//si lo es sumamos ese mismo valor
      total += parseFloat($(this).val());

    }

  });

  //agregaos el valor al input que corresponde
  document.getElementById('total_gr').value = total;

}



function sumarcost() {

  var total = 0;

  $(".cost").each(function() {

    if (isNaN(parseFloat($(this).val()))) {

      total += 0;

    } else {

      total += parseFloat($(this).val());

    }

  });

  document.getElementById('total_cost').value = total;

}
	
<body>

<h1>Creación de factura</h1>
	
	<form action="pfactura.php" method="post" autocomplete="off">
		<fieldset>
	    <legend>Seleccione un cliente y luego presiona buscar:</legend>
			<?php
$result = mysqli_query($connex,"SELECT * FROM clientes ORDER by nomcli desc");
 $row_cnt = mysqli_num_rows($result);//contar resultados totales	  		
?>	
 
     <td><select name="nomcli" id="nomcli">  
                <option value="-" selected="selected">Seleccione un cliente</option>  
                <?php
				$sqnomape = "SELECT * FROM clientes ";
			$renomape = mysqli_query($connex, $sqnomape);
			if (mysqli_num_rows($renomape) > 0) {
//Condición para validar si un registro ya existe.
			while($rownomape = mysqli_fetch_assoc($renomape)) {

			
?>
               <option value='<?php echo $rownomape["nomcli"]; ?>' required> <?php echo  $rownomape["nomcli"]; ?>  </option>
                <?php  
	   }
			}
	 ?> 
              </select></td>
		
		
		<input name="buscar" type="submit" name="buscar" value="buscar" title="Buscar." />

	
		 </fieldset>
</form>
	<?php
 $nomcli2 = $_POST['nomcli'];//Nombre del cliente
	
    ?>
	
	
	<form action="pfactura2.php" autocomplete="off" method="post">
		<fieldset>
			<legend>Llene los campos para crear la factura.</legend><fieldset>
			
	<?php  ?>
	
			<?php
			$sql = "SELECT * FROM clientes WHERE nomcli = '$nomcli2'";
$result = mysqli_query($connex, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
 ?>
			<table width="auto" border="1">
  <tbody>
    <tr>
      <td>Nombre del cliente</td>
      <td><input type="text" name="nomcli" readonly value="<?php echo $row["nomcli"]; ?>"></td>
		 <td>Limite de crédito:<input type="text" readonly size="10" value="<?php echo $row["licred"]; ?>"></td>
		
    </tr>
    <tr>
      <td>Código del cliente</td>
      <td><input type="text" name="codcli" readonly value="<?php echo $row["id"]; ?>"></td>
		<td>Fecha de facturación: <input type="date" name="fech" required ></td>
    </tr>
	  <tr>
      <td>Dirección</td>
      <td><input type="text" readonly value="<?php echo $row["dir"]; ?>"></td>
    </tr>
	   <tr>
      <td>Tel:</td>
      <td><input type="text" readonly size="10" value="<?php echo $row["tel"]; ?>">Cel:<input type="text" readonly size="10" value="<?php echo $row["cel"]; ?>"></td>
	  
	  </tr>
	  <tr>
      <td>Acarreo:</td>
      <td><input type="text" name="acarreo" size="50"></td>
		  <td rowspan="3"><textarea placeholder="Comentario"rows="4" cols="50" name="coment" >
</textarea></td>
	  </tr>
	  <tr>
	  <td>Desde:</td>
      <td><input type="text" name="desde" size="50"></td>
	  
	  </tr>
	  <tr>
	  <td>Hacia:</td>
      <td><input type="text" name="hacia" size="50" ></td>
    </tr>
  </tbody>
</table>
			

	<div class="container">

    <input type="button" value="Añadir fila" onClick="addRow('dataTable')"/>

    <form name="add_name" id="add_service">

        <table id="dataTable" class="form" border="1">
            <tbody>
            <tr id='row_0'>

                <td>
                    <label>Service</label>
                    <input type="text"  name="service[]">
                </td>
                <td>
                    <label>Quantity</label>
                    <input type="text" class="qty" value="1" size="5" readonly name="qty[]" oninput="calculate('row_0')">
                </td>
                <td>
                    <label for="price">Price</label>
                    <input type="text" class="cost"  name="cost[]" oninput="calculate('row_0')" onkeyup="sumarcost()">
                </td>
				 <td>
                    <label for="gr">gr</label>
                    <input type="text" class="gr"   name="gr[]" oninput="calculate('row_0')" onkeyup="sumargr()">
                </td>
                <td>
                    <label for="total">Importe</label>
                    <input type="text" class="subtotal"  readonly name="subtotal[]">

                </td>

                <td>
                    <input type="button" class="remove" value="Remove" onclick="removeRow('dataTable', '0');">
                </td>
            </tr>
            </tbody>
        </table>

		<table>
      
			<tr><td>SUB-Total</td><td><input type="text" class="" placeholder="Total de costos" id="total_cost" readonly></td></tr>
			<tr><td>GR:</td><td><input type="text" class="" placeholder="total gr" id="total_gr" readonly></td></tr>
          <tr><td> Total:</td><td> <input type="text" class="" placeholder="Grand total" id="grand_total" readonly></td></tr>
        

       <tr><td> Crear factura:</td><td> <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit"/></td></tr>
		</table>
    </form>

</div>
			
			
<?php 
    }
} else {
    echo "0 results";
}
			
?>
			
			

</form>
</body>

2
  • 1
    Te refieres al código de PHP para crear tu tabla? el 10 feb. 2020 a las 16:26
  • el código que está arriba del div div class="container" tiene algo que no permite que debajo lo demas sume el 10 feb. 2020 a las 16:29

1 respuesta 1

2

El código funciona cuando eliminas la parte de PHP + MySQLi porque tienes error al momento de imprimir tus variables PHP, recuerda si vas a imprimir una variable PHP dentro de un atributo HTML en este caso el value="" si utilizas comillas dobles " " entonces el índice de tu variable tiene que ir con comillas simples ' ' o viceversa, en caso de utilizar un índice numérico este iría sin comillas ni dobles ni simples. Ejemplo: value="<?php echo $row['nomcli'];?>" o value='<?php echo $row["nomcli"];?>'

En caso de usar indice numérico: value="<?php echo $row[0];?>"

function addRow(tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        if (rowCount < 10) {
            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;
            row.id = 'row_' + rowCount;
            for (var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.outerHTML = table.rows[0].cells[i].outerHTML;
            }
            var listitems = row.getElementsByTagName("input")
            for (i = 0; i < listitems.length - 1; i++) {
                listitems[i].setAttribute("oninput", "calculate('" +
                    row.id + "')");
            }
            listitems[listitems.length - 1].setAttribute("onclick", "removeRow('dataTable', " + row.id.replace("row_", "") + ")");
        } else {
            alert("Maximum 10.");

        }
    }


    function removeRow(tableID, index) {
        //Removing the row
        var table = document.getElementById(tableID);
        table.deleteRow(index);
        //Modifying the ids of subsequent rows
        var rowCount = table.rows.length;
        for (var i = index; i < rowCount; i++) {
            table.rows[i].id = "row_" + i;
            table.rows[i].getElementsByClassName("remove")[0].setAttribute("onclick", "removeRow('dataTable', " + i + ");");
        }
        //Handling the counts
        grandtotal();
    }


    function calculate(elementID) {
        var mainRow = document.getElementById(elementID);
        var myBox1 = mainRow.querySelectorAll('[class=qty]')[0].value;
        var myBox2 = mainRow.querySelectorAll('[class=cost]')[0].value;
		var myBox3 = mainRow.querySelectorAll('[class=gr]')[0].value;
        var total = mainRow.querySelectorAll('[class=subtotal]')[0];
        var myResult1 = myBox1 * (myBox2 + myBox3);
		
        total.value = myResult1;
		
		
		
		
		

        grandtotal();
	  
    }

    function grandtotal(){

        //calculation script
        var $form = $('#add_service'),
            $sumDisplay = $('#grand_total');

        var $summands = $form.find('.subtotal');
        var sum = 0;
        $summands.each(function ()
        {
            var value = Number($(this).val());
            if (!isNaN(value)) sum += value;
        });

        $sumDisplay.val(sum);
    }
	
	
	function sumargr() {

  var total = 0; //inicimos una variable para concatenarle la suma de los inputs

  $(".gr").each(function() { //recorremos el arreglo 

    if (isNaN(parseFloat($(this).val()))) { //con la propiedad this obtenemos el valor del input donde estemos escribiendo y validamos que no sea un número
    //si no lo es agregamos un 0

      total += 0;

    } else {
//si lo es sumamos ese mismo valor
      total += parseFloat($(this).val());

    }

  });

  //agregaos el valor al input que corresponde
  document.getElementById('total_gr').value = total;

}



function sumarcost() {

  var total = 0;

  $(".cost").each(function() {

    if (isNaN(parseFloat($(this).val()))) {

      total += 0;

    } else {

      total += parseFloat($(this).val());

    }

  });

  document.getElementById('total_cost').value = total;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<h1>Creación de factura</h1>
	
	<form action="pfactura.php" method="post" autocomplete="off">
		<fieldset>
	    <legend>Seleccione un cliente y luego presiona buscar:</legend>
			<?php
$result = mysqli_query($connex,"SELECT * FROM clientes ORDER by nomcli desc");
 $row_cnt = mysqli_num_rows($result);//contar resultados totales	  		
?>	
 
     <td><select name="nomcli" id="nomcli">  
                <option value="-" selected="selected">Seleccione un cliente</option>  
                <?php
				$sqnomape = "SELECT * FROM clientes ";
			$renomape = mysqli_query($connex, $sqnomape);
			if (mysqli_num_rows($renomape) > 0) {
//Condición para validar si un registro ya existe.
			while($rownomape = mysqli_fetch_assoc($renomape)) {

			
?>
               <option value='<?php echo $rownomape["nomcli"]; ?>' required> <?php echo  $rownomape["nomcli"]; ?>  </option>
                <?php  
	   }
			}
	 ?> 
              </select></td>
		
		
		<input name="buscar" type="submit" name="buscar" value="buscar" title="Buscar." />

	
		 </fieldset>
</form>
	<?php
 $nomcli2 = $_POST['nomcli'];//Nombre del cliente
	
    ?>
	
	
	<form action="pfactura2.php" autocomplete="off" method="post">
		<fieldset>
			<legend>Llene los campos para crear la factura.</legend><fieldset>
			
	<?php  ?>
	
			<?php
			$sql = "SELECT * FROM clientes WHERE nomcli = '$nomcli2'";
$result = mysqli_query($connex, $sql);

if (mysqli_num_rows($result) > 0) {
    //output data of each row
    while($row = mysqli_fetch_assoc($result)) {
 ?>
			<table width="auto" border="1">
  <tbody>
    <tr>
      <td>Nombre del cliente</td>
      <td><input type="text" name="nomcli" readonly value="<?php echo $row['nomcli']; ?>"></td>
		 <td>Limite de crédito:<input type="text" readonly size="10" value="<?php echo $row['licred']; ?>"></td>
		
    </tr>
    <tr>
      <td>Código del cliente</td>
      <td><input type="text" name="codcli" readonly value="<?php echo $row['id']; ?>"></td>
		<td>Fecha de facturación: <input type="date" name="fech" required ></td>
    </tr>
	  <tr>
      <td>Dirección</td>
      <td><input type="text" readonly value="<?php echo $row['dir']; ?>"></td>
    </tr>
	   <tr>
      <td>Tel:</td>
      <td><input type="text" readonly size="10" value="<?php echo $row['tel']; ?>">Cel:<input type="text" readonly size="10" value="<?php echo $row['cel']; ?>"></td>
	  
	  </tr>
	  <tr>
      <td>Acarreo:</td>
      <td><input type="text" name="acarreo" size="50"></td>
		  <td rowspan="3"><textarea placeholder="Comentario"rows="4" cols="50" name="coment" >
</textarea></td>
	  </tr>
	  <tr>
	  <td>Desde:</td>
      <td><input type="text" name="desde" size="50"></td>
	  
	  </tr>
	  <tr>
	  <td>Hacia:</td>
      <td><input type="text" name="hacia" size="50" ></td>
    </tr>
  </tbody>
</table>
</form>			

	<div class="container">

    <input type="button" value="Añadir fila" onClick="addRow('dataTable')"/>

    <form name="add_name" id="add_service">

        <table id="dataTable" class="form" border="1">
            <tbody>
            <tr id='row_0'>

                <td>
                    <label>Service</label>
                    <input type="text"  name="service[]">
                </td>
                <td>
                    <label>Quantity</label>
                    <input type="text" class="qty" value="1" size="5" readonly name="qty[]" oninput="calculate('row_0')">
                </td>
                <td>
                    <label for="price">Price</label>
                    <input type="text" class="cost"  name="cost[]" oninput="calculate('row_0')" onkeyup="sumarcost()">
                </td>
				 <td>
                    <label for="gr">gr</label>
                    <input type="text" class="gr"   name="gr[]" oninput="calculate('row_0')" onkeyup="sumargr()">
                </td>
                <td>
                    <label for="total">Importe</label>
                    <input type="text" class="subtotal"  readonly name="subtotal[]">

                </td>

                <td>
                    <input type="button" class="remove" value="Remove" onclick="removeRow('dataTable', '0');">
                </td>
            </tr>
            </tbody>
        </table>

		<table>
      
			<tr><td>SUB-Total</td><td><input type="text" class="" placeholder="Total de costos" id="total_cost" readonly></td></tr>
			<tr><td>GR:</td><td><input type="text" class="" placeholder="total gr" id="total_gr" readonly></td></tr>
          <tr><td> Total:</td><td> <input type="text" class="" placeholder="Grand total" id="grand_total" readonly></td></tr>
        

       <tr><td> Crear factura:</td><td> <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit"/></td></tr>
		</table>
    </form>

</div>
		
			
<?php 
    }
} else {
    echo "0 results";
}
			
?>
			

2
  • 1
    Muchas gracias Vick me has salvado, tengo mas proyectos pendientes quiero poder comunicarte contigo y pagarte, como hacemos? el 11 feb. 2020 a las 21:21
  • 1
    No hay de qué, y para nada mi estimado, lo hago para apoyar a la comunidad, cualquiera de nosotros te puede ayudar sin motivos de lucro. :D el 11 feb. 2020 a las 23:30

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.