I have the following case to solve:
In a table, where I add separate rows using the "Add" button, I have a combobox that brings data from the database and I need the input price_service to be automatically completed depending on the option selected in the table. combo of the same row.
Any suggestions? Thank you very much!
Here the code.
$(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;
// Obtenemos el total de filas (tr) del id "tabla"
var trs=$("#servicio tr").length;
var nuevaFila="<tr id='"+(cant)+"'>";
$('#contador-filas').val(cant)
nuevaFila+="<td><input class='form-control' name='servicio_cantidad["+(cant)+"]' placeholder='Cantidad"+(cant)+"' size='5' type='text' 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["+(cant)+"]' name='servicio_desc["+(cant)+"]' class='form-control custom-select'><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["+(cant)+"]' name='servicio_preciounitario["+(cant)+"]' placeholder='0,00' size='10' required /> </td>"+
"<td><input class='form-control' type='text' name='servicio_preciototal["+(cant)+"]' placeholder='0,00' size='10' required /> </td>"+
"<td><div id='del' class='btn btn-sm btn-danger'>Eliminar</div></td>";
nuevaFila+="</tr>";
$("#servicio").append(nuevaFila);
$('#servicio_desc['+(cant)+']').on('change', function() {
var preciounitario;
var servicio = $(this).val();
$.ajax({
type: "POST",
url: "actioncomboServiciosEnRemitos.php",
dataType: "html",
data: servicio,
async : false,
success: function(respuesta) {
preciounitario = respuesta;
},
});
$('#servicio_preciounitario['+(cant)+']').val('');
$('#servicio_preciounitario['+(cant)+']').val(preciounitario);
});
});
});
$(function () {
$(document).on('click', '#del', function (event) {
event.preventDefault();
$(this).closest('tr').remove();
});
});
<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>
</tbody>
</table>