I'm developing an application, where I have a dropdown, whose content shows a number with the change. All in a dynamic form with Jquery and the append() method.
The problem is that it works for me in the first field of the form, but after I add with append the function cargaLotes() does not work. Please help
This is the code:
</tr>
<tr>
<td>
<select class="form-control" id="id_producto" name="id_producto[]" onchange="cargaLotes();">
<option selected>Seleccione...</option>
<?php
foreach($data_productos as $dat3){
$id_producto = $dat3['id_producto'];
$desc_producto = $dat3['desc_producto_lab'];
?>
<option value="<?php echo $id_producto; ?>">
<?php echo $desc_producto; ?>
</option>
<?php }?>
</select>
</td>
<td>
<select class="form-control" id="id_lote" name="id_lote[]">
<option>Seleccione...</option>
</select>
</td>
<td><input type="text" id="num_lote" name="num_lote[]" class="form-control"></td>
<td><input type="date" id="fecha_vencimiento" name="fecha_vencimiento[]" class="form-control"></td>
<td><button class="btn btn-primary addItemBtn" id="addItemBtn">(+)</button></td>
</tr>
</table>
<center>
<button type="submit" class="btn btn-success w-10" id="addCompra" name="addCompra">Registrar compra</button>
</center>
</div>
function cargaLotes(){
$("#id_producto option:selected").each(function(){
var id_producto = $(this).val();
$.post("get_lotes.php",{id_producto:id_producto}, function(data){
$("#id_lote").html(data);
});
});
}
$(document).ready(function(){
var form_detalle = `
<tr>
<td>
<select class="form-control" id="id_producto" name="id_producto[]" onchange="cargaLotes();">
<option selected>Seleccione...</option>
<?php
foreach($data_productos as $dat3){
$id_producto = $dat3['id_producto'];
$desc_producto = $dat3['desc_producto_lab'];
?>
<option value="<?php echo $id_producto; ?>">
<?php echo $desc_producto; ?>
</option>
<?php }?>
</select>
</td>
<td>
<select class="form-control" id="id_lote" name="id_lote[]">
<option>Seleccione...</option>
</select>
</td>
<td><input type="text" id="num_lote" name="num_lote[]" class="form-control"></td>
<td><input type="date" id="fecha_vencimiento" name="fecha_vencimiento[]" class="form-control"></td>
<td><button class="btn btn-danger removeItemBtn" id="removeItemBtn">(-)</button></td>
</tr> `;
var max = 4; //MAXIMO DE FILAS DINAMICAS POR INSERTAR
var x = 1;
// FUNCION PARA AGREGAR LAS FILAS DINAMICAS
$(".addItemBtn").click(function(e){
e.preventDefault();
if(x <= max){
$("#tablaDetallesCompras").append(form_detalle);
x++;
}
});
// FUNCION PARA ELIMINAR LAS FILAS DINAMICAS AGREGADAS CON LA FUNCIÓN AGREGADA
$("#tablaDetallesCompras").on('click', '.removeItemBtn', function(e){
e.preventDefault();
$(this).closest('tr').remove();
x--;
});