Jquery dependent values in several rows

0

I have a button that adds, on the one hand, a row in a table with fields to fill. Also, with the same button, a row is added to another table, where some dependent data of the first table is completed. The problem is that when you add two rows or more, the dependent data is only replicated in the first row of the second table.

Here the code:

<script type="text/javascript">
$(document).ready(function(){

$("#add").click(function(){
cant = $('#contador-filas').val();
cant++;
// Obtenemos el numero de columnas (td) que tiene la primera fila
// (tr) del id "tabla"
var tds=$("#servicio tr:first td").length;
var tds=$("#TablaCadete tr:first td").length;
// Obtenemos el total de filas (tr) del id "tabla"
var trs=$("#servicio tr").length;
var trs=$("#TablaCadete tr").length;
var nuevaFila="<tr id='"+(cant)+"'>";
var nuevaFilaCadete="<tr id='"+(cant)+"'>";


$('#contador-filas').val(cant)
nuevaFila+="<td><input class='form-control' id='servicio_cantidad' name='servicio_cantidad["+(cant)+"]' placeholder='Cantidad"+(cant)+"' size='5' type='text' value='1' onBlur='Calcular(this);' required /> </td>"+
"<td><?php include ("includes/conexion.php"); $resultServicios = mysql_query("SELECT * FROM listasyservicios WHERE id_listadeprecios = '$ListaDePreciosSucursal' ORDER BY id_listasyservicios ASC"); ?><select id='servicio_desc' name='servicio_desc["+(cant)+"]' class='form-control custom-select' onBlur='Calcular(this);'><option value=''>-Seleccione Servicio-</option><?php while($rowServicio= mysql_fetch_object($resultServicios)){echo "<option value=".$rowServicio->id_listasyservicios.">";echo "".$rowServicio->id_servicio." - ".$rowServicio->nombreservicio."</option>";} ?></select></td>"+

"<td><input class='form-control' type='text' id='servicio_preciounitario' name='servicio_preciounitario["+(cant)+"]' placeholder='0,00' size='10' onBlur='Calcular(this);' required /> </td>"+

"<td><input class='form-control totalservicio' type='text' id='servicio_preciototal' name='servicio_preciototal["+(cant)+"]' placeholder='0,00' size='10' readonly /> </td>"+

"<td><div id='del' class='btn btn-sm btn-danger'>Eliminar</div></td>";

nuevaFila+="</tr>";

$("#servicio").append(nuevaFila);


nuevaFilaCadete+="<td><input class='form-control' id='cod_cadete' name='cod_cadete["+(cant)+"]' value='<?php echo ''.$Asignado_Id_Empleado.''; ?>' size='5' type='text' required /> </td>"+
"<td><?php include ("includes/conexion.php"); $resultCadete = mysql_query("SELECT id_empleado, apellido, nombre FROM empleados WHERE id_puesto = 11 ORDER BY id_empleado ASC"); ?><select id='cadete_desc' name='cadete_desc["+(cant)+"]' class='form-control custom-select'><option value=''>-Seleccione Cadete-</option><?php while($rowCadete= mysql_fetch_object($resultCadete)){echo "<option value=".$rowCadete->id_empleado.""; if($Asignado_Id_Empleado==$rowCadete->id_empleado){echo " selected";}; echo">";echo "".$rowCadete->id_empleado." - ".$rowCadete->apellido.", ".$rowCadete->nombre."</option>";} ?></select></td>"+

"<td><input class='form-control' id='servicio_cantidad_cadete' name='servicio_cantidad_cadete["+(cant)+"]' placeholder='Cantidad"+(cant)+"' size='5' type='text' value='1' onBlur='Calcular(this);' required /> </td>"+
"<td><?php include ("includes/conexion.php"); $resultServicios = mysql_query("SELECT * FROM listasyservicios WHERE id_listadeprecios = '$ListaDePreciosSucursal' ORDER BY id_listasyservicios ASC"); ?><select id='servicio_desc_cadete' name='servicio_desc_cadete["+(cant)+"]' class='form-control custom-select' onBlur='Calcular(this);'><option value=''>-Seleccione Servicio-</option><?php while($rowServicio= mysql_fetch_object($resultServicios)){echo "<option value=".$rowServicio->id_listasyservicios.">";echo "".$rowServicio->id_servicio." - ".$rowServicio->nombreservicio."</option>";} ?></select></td>"+

"<td><input class='form-control' type='text' id='servicio_preciounitario_cadete' name='servicio_preciounitario_cadete["+(cant)+"]' placeholder='0,00' size='10' onBlur='Calcular(this);' required /> </td>"+

"<td><input class='form-control totalservicio' type='text' id='servicio_preciototal_cadete' name='servicio_preciototal_cadete["+(cant)+"]' placeholder='0,00' size='10' readonly /> </td>"+

"<td><div id='del' class='btn btn-sm btn-danger'>Eliminar</div></td>";

nuevaFilaCadete+="</tr>";

$("#TablaCadete").append(nuevaFilaCadete);

});

});


$(function () {
    $(document).on('click', '#del', function (event) {
		var total = document.getElementById('TotalServicios');
        total.innerHTML = parseFloat(total.innerHTML) - parseFloat(this.parentNode.parentNode.childNodes[3].childNodes[0].value);
        event.preventDefault();
        $(this).closest('tr').remove();
		
		Calcular(event.target);
    });
});

$(document).ready(function () {
         $("#servicio_cantidad").blur(function () {
              var value = $(this).val();
              $("#servicio_cantidad_cadete").val(value);
          });
      });



$(function () {
$('#servicio').on('change', 'select', function() {
  
  var servicioVal = $(this).val(); 

  //petición ajax
    $.ajax({
    type: "POST",
    url: "actioncomboServiciosEnRemitos.php",
    dataType: "json",

    data: { "servicioVal" : servicioVal },
    async : false,
    success: function(respuesta){
	preciounitario =  respuesta[0];	
	preciocosto =  respuesta[1];	
	servId =  servicioVal;
}
	
	
  });

  var $nextInput = $(this).closest("td").next().find("input:text");
  $nextInput.val(preciounitario);  
  var $ServicioIdCadetes = $("#servicio_desc_cadete").closest("td").find("select");
  $ServicioIdCadetes.val(servId);  
  var $PrecioUnitarioCadetes = $("#servicio_preciounitario_cadete").closest("td").find("input:text");
  $PrecioUnitarioCadetes.val(preciocosto);  

});
});

function Calcular(ele) {
            var cantidad = 0, precunit = 0, totalitem = 0 ;
			
            var tr = ele.parentNode.parentNode;
            var nodes = tr.childNodes;
        
            for (var x = 0; x<nodes.length;x++) {
               
                if (nodes[x].firstChild.id == "servicio_cantidad") {
                    cantidad = parseFloat(nodes[x].firstChild.value,10);
                }
                if (nodes[x].firstChild.id == "servicio_preciounitario") {
                    precunit = parseFloat(nodes[x].firstChild.value,10);
                }
                if (nodes[x].firstChild.id == "servicio_preciototal") {
                    anterior = nodes[x].firstChild.value;
                    totalitem = parseFloat((precunit*cantidad),10);
                    nodes[x].firstChild.value = totalitem;
				}
				if (nodes[x].firstChild.id == "servicio_cantidad_cadete") {
                    cantidad = parseFloat(nodes[x].firstChild.value,10);
                }
                if (nodes[x].firstChild.id == "servicio_preciounitario_cadete") {
                    precunit = parseFloat(nodes[x].firstChild.value,10);
                }
                if (nodes[x].firstChild.id == "servicio_preciototal_cadete") {
                    anterior = nodes[x].firstChild.value;
                    totalitem = parseFloat((precunit*cantidad),10);
                    nodes[x].firstChild.value = totalitem;	
					
					
				if (totalitem.innerHTML == "NaN") {
                totalitem.innerHTML = 0;
                // 
            }
                }
            }
             calcular_total();   
        }


function calcular_total() {
	importe_total = 0
	$("#servicio .totalservicio").each(
		function(index, value) {
			importe_total = importe_total + eval($(this).val());
		}
	);
	var importe_totalEntero = importe_total; 
	var importe_total2Dec = importe_totalEntero.toFixed(2); 
	$("#TotalServiciosTabla #TotalServiciosInput").val(importe_total2Dec);
	$("#TotalServiciosTabla #TotalServicios").html(importe_total2Dec);
}
		
		
</script>
<table id="servicio">
						<thead id="borrarAncla">
						  <tr>
				<th>Cantidad</th>
				<th>Servicio</th>
				<th>Precio Unitario</th>
				<th>Total</th>
				<th><div id="add" class="btn btn-sm btn-success">Agregar</div></th>
						  </tr>
						</thead>


<tbody>
<input type="hidden" id="contador-filas" value="0">	
<?
			
			$resultServ = mysql_query("SELECT serviciosenremitos.id_servicioenremito, serviciosenremitos.id_remito, serviciosenremitos.id_servicio FROM serviciosenremitos WHERE serviciosenremitos.id_remito = '$idRemito' ORDER BY serviciosenremitos.id_servicioenremito ASC "); 
			
			if ($rowServicios= mysql_fetch_array($resultServ)){ 
			do { 
			echo '<tr>';
			echo '<td><input name="servicio_cantidad" class="form-control" id="servicio_cantidad" placeholder="Cantidad" size="10" type="text" value="Cantidad"></td>';
			echo '<td><input name="servicio_desc" class="form-control" id="servicio_desc" placeholder="Servicio" size="15" type="text" value="'.$rowServicios["id_servicio"].'"></td>';
			echo '<td><input name="servicio_preciounitario" class="form-control" id="servicio_preciounitario" placeholder="0,00" size="10" type="text"></td>';
			echo '<td><input name="servicio_preciototal" class="form-control" id="servicio_preciototal" placeholder="0,00" size="10" type="text" ></td>';
			echo '</tr>';
			} while ($rowServicios = mysql_fetch_array($resultServ)); 
			} else { 
			echo 'No hay servicios cargados para este remito.'; 
			}
			?>
</tbody>
					  </table>
<table id="TotalServiciosTabla">
						<thead>
						  <tr>
						  <td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<th>TOTAL $</th>
							<td><div id="TotalServicios" style="text-align:right;font-weight: bold;"> <input class="form-control" id="TotalServiciosInput" type="hidden" >
							</div></td>
						  </tr>
						</tbody>
					  </table>
</div>
<div class="form-title">

<div class="form-group"> 
<label for="Prestador">Prestador</label> 
<input type="hidden" name="CodPrestador" class="form-control" id="CodPrestador"> 
<select name="Prestador" id="Prestador" class="form-control">
<?php
			$resultAsignado_Id_Empleado = mysql_query("SELECT id_empleado, apellido, nombre FROM empleados WHERE id_puesto = 11 ORDER BY id_empleado ASC  
					   "); 
					   
			if ($rowAsignado_Id_Empleado = mysql_fetch_array($resultAsignado_Id_Empleado)){ 
			do { 
			echo '<option value="'.$rowAsignado_Id_Empleado["id_empleado"].'"';
			if($Asignado_Id_Empleado==$rowAsignado_Id_Empleado["id_empleado"]){echo 'selected';};
			echo '>';
			echo ''.$rowAsignado_Id_Empleado["id_empleado"].' - '.$rowAsignado_Id_Empleado["apellido"].', '.$rowAsignado_Id_Empleado["nombre"].'</option>';
			
			}
			while ($rowAsignado_Id_Empleado = mysql_fetch_array($resultAsignado_Id_Empleado)); 
			} else { 
			echo 'No hay Cadetes.'; 
			}
			?>
</select>
</div>
</div>	
<div class="w3l-table-info">
<table id="TablaCadete">
						<thead>
						  <tr>
							<th>Cod. Cadete</th>
							<th>Apellido y Nombre</th>
							<th>Cantidad</th>
							<th>Descripci&oacute;n</th>
							<th>Precio Unitario</th>
							<th>Total</th>
						  </tr>
						</thead>
						<tbody>

						</tbody>
					  </table>
<table id="table">
						<thead>
						  <tr>
						  <td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<th>TOTAL</th>
							<td><div style="text-align:right;font-weight: bold;"> $ XXXXX</div></td>
						  </tr>
						</tbody>
					  </table>
</div>
    
asked by pointup 05.04.2018 в 22:09
source

1 answer

1

What you have to do is use just the ids that you generate when you add a tr to be able to link the functionality with the same% tr of the other table. Being your example very big and being in php I leave you a minimum example so that you understand the logic that I propose.

var cant = 0;
$("#load").click(function() {
  cant++;
  var tr = '<tr id="' + cant + '">' +
    '<td>' + cant + '</td><td><select> ' +
    '<option value="1">Uno</option>' +
    '<option value="2">Dos</option>' +
    '<option value="3">Tres</option>' +
    '</select></td></tr>';
  var tr2 = '<tr id="' + cant + '">' +
    '<td>' + cant + '</td><td><select id="servicio_desc_cadete"> ' +
    '<option value="1">Prueba 1</option>' +
    '<option value="2">Prueba 2</option>' +
    '<option value="3">Prueba 3</option>' +
    '</select></td></tr>';

  $("#servicio").append(tr);
  $("#TablaCadete").append(tr2);

});

$("#servicio").on("change", "select", function() {

  // en esta funcion primero ubica al tr padre para hacer el cambio en el elemento
  // asi no se cruzara el  elemento que buscas
  //obetnemos el valor
  var value = $(this).val();
  //obtenemos el tr padre para tener el id generado y usarlo en la otra tabla
  var tr = $(this).parent().parent();  
  var id = tr.attr("id");

  //console.log(id);
  
  ///cambias la linea 
  //  var $ServicioIdCadetes = $("#servicio_desc_cadete").closest("td").find("select");
  //porla siguiente que busca en tu tabla el id para despues buscar el select
  var select = $("#TablaCadete").find("#"+ id).find("#servicio_desc_cadete");

  select.val(value);
});
table {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="load">Agregar</button>
<br>
<hr>
<br>
<table id="servicio" class="table">
  <thead>
    <tr>
      <th>Row</th>
      <th>Select</th>
    </tr>
    <thead>
      <tbody>
      </tbody>
</table>
<br>
<hr>
<br>
<table id="TablaCadete" class="table">
  <thead>
    <tr>
      <th>Row</th>
      <th>Input</th>
    </tr>
    <thead>
      <tbody>
      </tbody>
</table>
    
answered by 05.04.2018 / 23:15
source