jQuery Sum or Multiply values always without event trigger - javascript

Hi people i have a dynamic table (add rows from ajax requests) and i need sum and multiply values always (without a trigger event).
i have already a functions that make it with the event (blur) but i don't wanna make it by using the blur trigger.
There is a way for do it?
My code:
$.fn.sumValues = function() {
var sum = 0;
this.each(function() {
if ($(this).is(':input')) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
});
return sum;
};
function totaliza() {
var total_recep = $('input[name^="costot"]').sumValues();
$('#total_art').val(total_recep);
}
var counter = 0;
$(document).on('click', '#bt_add', function(e) {
counter++;
var tr = '<tr id="art_' + counter + '">';
tr = tr + '<td><button name="del_art' + counter + '" id="del_art' + counter + '" class="btn btn-default btn-xs del_art" type="button">DEL</button></td>';
tr = tr + '<td><input name="cbarra' + counter + '" id="cbarra' + counter + '" class="form-control" value="02020202" readonly></td>';
tr = tr + '<td><input name="art' + counter + '" id="art' + counter + '" class="form-control" value="ARTICULO" readonly></td>';
tr = tr + '<td><select name="und' + counter + '" id="und' + counter + '" class="form-control list"></select></td>';
tr = tr + '<td><input name="cal' + counter + '" id="cant' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="cal' + counter + '" id="costou' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="costot' + counter + '" id="costot' + counter + '" class="form-control cal" readonly value="0"></td>';
tr = tr + '</tr>';
$("#inv_recep_det tbody").append(tr);
$('.form-control').change(function() {
var number = this.name.replace('cal', '');
var costot = ($('#cant' + number).val() * $('#costou' + number).val())
$('input[name^="costot' + number + '"]').val(costot);
totaliza();
});
$('.del_art').click(function() {
var number = this.name.replace('del_art', '');
$('#art_' + number).remove();
totaliza();
});
});
https://jsfiddle.net/JuJoGuAl/kpLs9zcg/
Something like that?
http://jsfiddle.net/JuJoGuAl/0vx64u2y/

Rather than continuing in comments, I thought an answer might be of better use. Currently, you use:
$(".form-control).change(...)
to trigger the update. Some browsers may force you to lose the focus on an element to actually trigger that. Instead, change that line to:
$(".form-control").on("input", function(){ ... })
This has been discussed here: What is the difference between "change" and "input" event for an INPUT element
Other than that, I've made no changes to your fiddle: https://jsfiddle.net/snowMonkey/kpLs9zcg/5/

Related

How to get price total of dynamically created rows?

I want to SUM the price of all dynamically created rows and display into total input field..I have tried some things but not working for me.I have posted my script and image that explains how it should works. Everything is working and saving in database just want total amount of all items. Please see image for clear concept. Total of 1st row is saving in total but not working for dynamically created rows.
Image:
It should work like this
Html:
<div class="form-group">
<label>Total</label>
<input readonly type="text" id="total_amount" class="form-control"
name="total_amount">
</div>
Script:
<script>
var counterr = 1;
$(document).ready(function () {
$('#unit_price,#item_quantity').change(function () {
// alert();
var unitPrice = $('#unit_price').val();
// console.log(unitPrice);
var quantity = $('#item_quantity').val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price').val(total);
$('#total_amount').val(total);
});
// Input Fields
var maxField = 100; //Input fields increment limitation
var addButton = $('#add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
$(addButton).click(function (e) {
e.preventDefault();
counterr++;
//Check maximum number of input fields
if (counterr < maxField) {
fieldHTML = makeNewRow(counterr);
$(wrapper).append(fieldHTML); //Add field html
// $('#department-'+counterr).select2();
// console.log("Unit price", counterr);
$('.unit_price' + counterr).change(function () {
// console.log("hello");
var unitPrice = $('.unit_price' + counterr).val();
// console.log(unitPrice);
var quantity = $('#item_quantity' + counterr).val();
// console.log(quantity);
var total = (unitPrice * quantity).toFixed(0);
$('#total_price' + counterr).val(total);
$('#total_price').each(function() {
subtotal += parseFloat($(this).val());
console.log('test',subtotal);
});
$('#total_amount').val(subtotal);
});
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('#newrow').remove(); //Remove field html
counterr = counterr--; //Decrement field counter
})
});
function makeNewRow(counterr) {
return '<div class="row" id="newrow">' +
'<div class="col-md-4">' +
'<div class="form-group">' +
'<select onChange="getPurchasePrice(this.value);" style="background-color: #f5f6f9" id="item_name' + counterr + '" class="form-control dep"' +
'placeholder="Enter Item" name="testing[]"' + '>' +
'<option value = "">Select Item</option>' + '>' +
'#foreach($items as $item)' + '>' +
'<option value = "{{$item->id}}">{{$item->item_name}}</option>' + '>' +
'#endforeach' + '>' +
'</select>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="item_quantity' + counterr + '" class="form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<input style="background-color: #f5f6f9" type="number" id="unit_price' + counterr + '" class="unit_price' + counterr + ' form-control"' +
'placeholder="Enter.." name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<div class="col-md-3">' +
'<div class="form-group">' +
'<input value="0" style="background-color: #f5f6f9" disabled type="text" id="total_price' + counterr + '" class="form-control"' +
'placeholder="Total" name="testing[]"' + '>' +
'</div>' +
'</div>' +
'<a style="height:40px;margin-left:25px" href="javascript:void(0);" class="btn btn-danger remove_button">X</a>' +
'</div>'; //New input field html
}
/*function removeDiv(no){
$("#testingrow-"+no).remove();
x--;
}*/
</script>
Add a function to recalculate the grand total 'recalcGrandTotal'
var recalcGrandTotal = function() {
var grandTotal = 0; // Declare a var to hold the grand total
$("[id^=total_price]").each(function() { // Find all elements with an id that starts with 'total_price'
grandTotal += parseInt($(this).val()); // Add the value of the 'total_price*' field to the grand total
})
$('#total_amount').val(grandTotal); // append grand total amount to the total field
}
Then, hook this function up to the 'total price' recalculation function:
Find
$('#total_price' + counterr).val(total);
Add after:
recalcGrandTotal();
To substract from grand total upon removal of an item, hook this function up to the item removal function. Find:
counterr = counterr--; //Decrement field counter
Add after:
recalcGrandTotal();

Deleting selected Item from Panel -JS

Below is my code which works this way. when user selects checkbox, it appends the selected item name and price and calculates the sub total based on the quantity the user types in.
Now when a user deselects a checkbox, the item deselected disappears and the total reduces the total to the old total (previous total).
What I want to achieve is, my html below I can icon fa fa-close which I want it to perform like how when a checkbox is deselected. So when a user clicks on the icon, it removes the respective item and also reduces the total to the old total
function order(food) {
var ad = JSON.parse(food.dataset.food),
existing;
if (food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> ' +
'<input type="hidden" value=' + ad.id + ' data-id="' + ad.id + '" name="food_id[]" />' +
'<table style="width:100%;" class="table" id="tables">' +
'<thead>' +
'<thead>' +
'<tbody id="item_list">' +
'<tr>' +
'<td class="icon" ><i class="fa fa-close"></i></td>' +
'<td class="name" >' + ad.name + '</td>' +
'<td class="price" data-price="' + ad.price + '">' + ad.price + '</td>' +
'<td><p class="total" ><span class="line-total" name="total" id="total"></span></p></td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>'
)
}
} else {
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.checkout span').text(function(index, oldtext) {
console.log('this is my old text ' + oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
$('.panel').on('keyup', '.quantity', function() {
order_container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
order_container.find(".total span").text(quantity * price);
order_container.find(".pts-total span").text(quantity * points);
sum = 0;
points = 0;
$(".line-total").each(function() {
sum = sum + Number($(this).text());
})
$(".pts-total").each(function() {
points = points + Number($(this).text());
})
$('.checkout span').text(sum);
});
You can try this simple click event
$('.panel').on('click','.fa.fa-close',function(){
$(this).closest('.container').remove();//remove the current element
var sum = 0;
$(".line-total").each(function(){
sum = sum + Number($(this).text());
});//calculate the new sum
$('.checkout span').text(sum);
})

How to get the value of a cell from an html table after deleting the row?

I have a button that when I click on it, it dynamically generates rows in the table, it also generates a button to remove that row.
The problem I have is every time a row is generated, the value of a cell is summed in a text field, and when I remove that row I need to subtract the value from that cell to my text field.
That is why I need to get the value of that cell when it is removed.
This is my button tha generates the dynamic row in the table:
<input type="button" name="agregar" id="agregar" value="Agregar" class="btn btn-primary"/>
And this is the jQuery code for the click event of the button:
$("#agregar").click(function () {
var productoId = $("#productoId").val();
var productoDescripcion = $("#productoDescripcion").val();
var productoPrecio = $("#productoPrecio").val();
var productoCantidad = $("#productoCantidad").val();
var productoIva = $("#productoIva").val();
total = (productoPrecio * productoCantidad) - (((productoPrecio * productoCantidad) * productoIva) / 100);
subTotal = subTotal + total;
$("#totalAPagar").val(subTotal);
var presupuesto = '<tr>' +
'<td>' + productoId + '</td>' +
'<td>' + productoDescripcion + '</td>' +
'<td>' + productoPrecio + '</td>' +
'<td>' + productoCantidad + '</td>' +
'<td>' + productoIva + '</td>' +
'<td>' + total + '</td>' +
'<td class="eliminar-fila"><button id="eliminar" class="btn btn-danger eliminar" type="button"><span class="fa fa-remove"></span></button></td>' +
'</tr>';
$("#presupuestoDetalle tbody").append(presupuesto);
$(".eliminar").click(function () {
valor = $(this).find("td").eq(5).text();
$(this).parents("tr").fadeOut("normal", function () {
$(this).remove();
subTotal = subTotal - valor;
$("#totalAPagar").val(subTotal);
});
});
});
Inside this event click I have another event click on the "delete" button, which is the one in charge of removing the row. In this event click I want to get the value of the "total" cell like this:
valor = $(this).find("td").eq(5).text();
In order to be able to do this arithmetic operation:
subTotal = subTotal - valor;
But the field valor is in blank. How can i get the value of that cell?
I built a minimal verifiable sample here and found a few little points on the way:
You are assigning the click event listener for ".eliminar" potentially several times, when there are more than one lines in your table.
I changed that to a single assignment using .on().
Your valor was determined wrongly. It needs to be something like
valor = $(this).closest('tr').find("td").eq(5).text();
var subTotal=0,total=0;
$(function(){
$("#agregar").click(function(){
var productoId = $("#productoId").val();
var productoDescripcion = $("#productoDescripcion").val();
var productoPrecio = $("#productoPrecio").val();
var productoCantidad = $("#productoCantidad").val();
var productoIva = $("#productoIva").val();
total = (productoPrecio * productoCantidad) - (((productoPrecio * productoCantidad) * productoIva) / 100);
subTotal = subTotal + total;
$("#totalAPagar").val(subTotal);
var presupuesto = '<tr>' +
'<td>' + productoId + '</td>' +
'<td>' + productoDescripcion + '</td>' +
'<td>' + productoPrecio + '</td>' +
'<td>' + productoCantidad + '</td>' +
'<td>' + productoIva + '</td>' +
'<td>' + total + '</td>' +
'<td class="eliminar-fila"><button class="btn btn-danger eliminar" type="button">eliminar</button></td>' +
'</tr>';
$("#presupuestoDetalle tbody").append(presupuesto);
});
$('tbody').on("click",".eliminar",function(){
valor = $(this).closest('tr').find("td").eq(5).text();
$(this).parents("tr").fadeOut("normal", function () {
$(this).remove();
subTotal = subTotal - valor;
$("#totalAPagar").val(subTotal);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="productoId" name="productoId" value="123"/> id<br/>
<input type="text" id="productoDescripcion" name="productoDescripcion" value="producto A"/> descr.<br/>
<input type="text" id="productoPrecio" name="productoPrecio" value="10" /> precio<br/>
<input type="text" id="productoCantidad" name="productoCantidad" value="3" /> cant.<br/>
<input type="text" id="productoIva" name="productoIva" value="19" /> iva
<input type="text" id="totalAPagar" name="totalAPagar" value="0"><br/>
<input type="button" name="agregar" id="agregar" value="Agregar" class="btn btn-primary"/>
<table id="presupuestoDetalle">
<tr><th>Id</th><th>Descripcion</th><th>Precio</th><th>Contidad</th><th>Iva</th><th>total</th></tr>
</table>
I forgot to put the .parents("tr") method in the expression like this:
valor = $(this).parents("tr").find("td").eq(5).html();
I suppose I did not find the 'td' selector before, so first I have to go to the parent selector with .parents ('tr') and then try to find the 'td' selector, and then i put the html() method instead of the .text() method.
Now I can get the value of the cell.

jquery fadeIn effect with <tr>

I am adding rows dynamically to a table based on selection yet I would like to add fadeIn effect.
I am posting the part in which I add the rows to table.
Any help will be appreciated.
(I am trying to use the fadeIn effect while adding newRow to table and removing tblGraphPattern content afterwards). I want to have the effect in the lines
$("table.selectPattern").append(newRow);
$("#tblGraphPattern tr").remove();
var newRow = $("<tr>");
newRow.attr("align","center");
newRow.css("outline", "thin solid");
for(var i = 1; i<counter;++i)
{
if($("#divSubject"+i+"").length>0)
{
var cols = "";
subjectText=$("#divSubject"+i+"").html();
if(subjectText=="Any")
{subjectVal = "?s"+selectCounter;}
else{subjectVal=$("#txtGraphSubject"+i+"").val();}
predicateText=$("#divPredicate"+i+"").html();
if(predicateText=="Any")
{predicateVal = "?p"+selectCounter;}
else{predicateVal=$("#txtGraphPredicate"+i+"").val();}
objectText=$("#divObject"+i+"").html();
if(objectText=="Any"){objectVal="?o"+selectCounter;}
else{
objectVal=$("#txtGraphObject"+i+"").val();
}
cols += '<tr><td align="right"><div id="divSelectSubject'+num+'">'+subjectText+'</div><input type="text" value="'+subjectVal+'" name="txtSelectSubject'
+ num + '" id="txtSelectSubject' + num + '"/></td>';
cols += '<td align="center"><div id="divSelectPredicate'+num+'">'+predicateText+'</div><input type="text" value="'+predicateVal+
'" name="txtSelectPredicate' + num + '" id="txtSelectPredicate' + num + '"/></td>';
cols += '<td align="left"><div id="divSelectObject'+num+'">'+objectText+'</div><input type="text" value="'+objectVal+
'" name="txtSelectObject' + num + '" id="txtSelectObject' + num + '"/></td></tr>';
newRow.append(cols);
}
num++;
}
selectCounter++;
newRow.append('<td><input type="button" class="ibtnDel" value="Delete"></td>');
$("table.selectPattern").append(newRow);
$("#tblGraphPattern tr").remove();
Make your newRow hidden by setting display:none; before appending it to table.selectPattern and then fadeIn after appending is done.
var newRow = $('<tr style="display:none;"></tr>');
// your remaining code
$("table.selectPattern").append(newRow);
$("#tblGraphPattern tr").remove();
newRow.fadeIn(2000);

Get variable from loop

I have a loop which is creating table:
for(m=1; m<7; m++){
document.getElementById('content').innerHTML +=
('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>')
}
In every row in second TD is button which must be assigned to every row. Each button has his own row. I want to alert m from the first TD exactly when i click button from that row. I mean if i will click button is switch2 i will get alert from m "2".
Here is the button code i tried:
var buttons = "#switch" + m
$(function() {
$(buttons).button();
$(buttons).click(function(){
alert(m);
});
});
This is not working because all of the buttons alerting last value from loop = 6.
I know it is confused but i hope you uderstand. Really appreciate your help
Change it to this:
$(function() {
var localM = m;
$(buttons).button();
$(buttons).click(function(){
alert(localM);
});
});
The problem is the alert binds to the variable m not the value of m. By allocating a local variable inside the closure you capture the value of m at that point in the loop.
you can also bind event another way, for sample
$("tr > td > input[type=checkbox]").function(e){
alert(event.target.id);
//OR
alert(this.id);
});
if you can add any class attribute in element
Then this is safe
$("tr > td > input[type=checkbox].switch").function(){
alert(event.target.id);
});
There is so many ways to do this. Here's one:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Populate Form
for (var m = 1; m <= 7; m++)
{
$('#content').append('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" class="clickMe" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>');
}
// Handle Click
$('.clickMe').click(function()
{
alert('You clicked on : ' + $(this).attr('id')); // alerts "switchN" e.g. switch1
// or //
alert('You clicked on : ' + $(this).attr('id').replace('switch', '')); // // alerts "N" e.g. 1
});
});
</script>
<table id="content"></table>
Here's a bit of a refactor (minus the button() plugin):
var $content = $('#content');
for (var m = 1; m < 7; m++) {
$content.append(
'<tr>' +
'<td>' + m + '</td>' +
'<td>' +
'<input type="checkbox" id="switch' + m + '">' +
'<label class="switch" data-num=' + m + ' for="switch' + m +'">Button ' + m + '</label>' +
'</td>' +
'</tr>'
);
}
$('label.switch').click(function(e) {
e.preventDefault();
alert($(this).data('num'));
});
JSFIDDLE

Categories

Resources