Created
March 24, 2020 06:04
-
-
Save jsegomez/8a652900d08d1b2749348266ca89fc38 to your computer and use it in GitHub Desktop.
Autocompletado de productos con jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="es" xmlns:th="http://www.thymeleaf.org"> | |
<body> | |
<script type="text/javascript" th:fragment="javascript"> | |
$(document).ready(function() { | |
$("#buscar_producto").autocomplete({ | |
source: function(request, response) { | |
$.ajax({ | |
url: "/facturas/cargar-productos/" + request.term, | |
dataType: "json", | |
data: { | |
term: request.term | |
}, | |
success: function(data) { | |
response($.map(data, function(item) { | |
return { | |
value: item.id, | |
label: item.nombre, | |
precio: item.precio, | |
}; | |
})); | |
}, | |
}); | |
}, | |
select: function(event, ui) { | |
if (itemsHelper.hasProducto(ui.item.value)) { | |
itemsHelper.incrementaCantidad(ui.item.value, ui.item.precio); | |
return false; | |
} | |
var linea = $("#platillaItemsFactura").html(); | |
linea = linea.replace(/{ID}/g, ui.item.value); | |
linea = linea.replace(/{NOMBRE}/g, ui.item.label); | |
linea = linea.replace(/{PRECIO}/g, ui.item.precio); | |
$("#cargarItemProductos tbody").append(linea); | |
itemsHelper.calcularImporte(ui.item.value, ui.item.precio, 1); | |
return false; | |
} | |
}); | |
$("form").submit(function(){ | |
$("#platillaItemsFactura").remove(); | |
}); | |
}); | |
var itemsHelper = { | |
calcularImporte: function(id, precio, cantidad) { | |
$("#total_importe_" + id).html(parseInt(precio) * parseInt(cantidad)); | |
this.calcularGranTotal(); | |
}, | |
hasProducto: function(id) { | |
var resultado = false; | |
$('input[name="item_id[]"]').each(function() { | |
if (parseInt(id) == parseInt($(this).val())) { | |
resultado = true; | |
} | |
}); | |
return resultado; | |
}, | |
incrementaCantidad: function(id, precio) { | |
var cantidad = $("#cantidad_" + id).val() ? parseInt($("#cantidad_" + id).val()) : 0; | |
$("#cantidad_" + id).val(++cantidad); | |
this.calcularImporte(id, precio, cantidad); | |
}, | |
eliminarLineaFactura: function(id){ | |
$("#row_" + id ).remove(); | |
}, | |
calcularGranTotal: function(){ | |
var total = 0; | |
$('span[id^="total_importe_"]').each(function(){ | |
total += parseInt($(this).html()); | |
}); | |
$('#gran_total').html(total); | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment