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);
})
Related
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();
I'm trying to insert a button in the end of each row of the table receitas but the buttons are being set at the start of the table instead of the end of each row.
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for(let i in receitas) {
if(receitas[i].tipo==aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> '+ receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td></td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
The line where I put all the properties into the table row (inside of for), I have an input which should be set at the end of the row but instead, it is going to the top of the table.
It's just a type error in the cell wrapping the button you're creating </td> instead of starting <td>
see belown snippet :
receitas = [
{tipo:"typ1",nome:"nome1",tempo:"tempo1",custo:"custo1",dificuldade:"dificuldade1"},
{tipo:"typ2",nome:"nome2",tempo:"tempo2",custo:"custo2",dificuldade:"dificuldade2"},
{tipo:"typ1",nome:"nome3",tempo:"tempo3",custo:"custo3",dificuldade:"dificuldade3"},
{tipo:"typ1",nome:"nome4",tempo:"tempo4",custo:"custo4",dificuldade:"dificuldade4"},
]
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for (let i in receitas) {
if (receitas[i].tipo == aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> ' + receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td><td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
mostraTabelaTeste("typ1","table");
<div id="table"></div>
You may need to add one more th for button column in first row. Like below:
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th><th> </th></tr>';
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/
my jQuery creates tables, but currently it keeps repeating the new tables under the previous ones when 'submit' button is clicked. How do I toggle it so it clears the previous table before showing the new table?
Any help would be great thanks!
<script type="text/javascript">
function call_everybody(){
display_results_table();
display_cyclist_results_table();
display_cyclist2_results_table();
}
function display_results_table() {
$("medal_table").empty();
$('<table id = "results_table">').appendTo('#medal_table');
$.get("sam2.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (results_obtained) {
$('<tr><td>Rank</td>' +
'<td>Country Name</td>' +
'<td>Population</td>' +
'<td>GDP</td>' +
'<td>Gold</td>' +
'<td>Silver</td>' +
'<td>Bronze</td>' +
'<td>Total</td></tr>').appendTo('#results_table');
for (var i = 0; i <= results_obtained.length; i++) {
$('<tr><td>' + (i+1) + '</td>' +
'<td>' + results_obtained[i].country_name + '</td>' +
'<td>' + results_obtained[i].population + '</td>' +
'<td>' + results_obtained[i].gdp + '</td>' +
'<td>' + results_obtained[i].gold + '</td>' +
'<td>' + results_obtained[i].silver + '</td>' +
'<td>' + results_obtained[i].bronze + '</td>' +
'<td>' + results_obtained[i].total + '</td></tr>').appendTo('#results_table');
}
},'json');
$('</table>').appendTo('#medal_table');
}
function display_cyclist_results_table() {
$("cyclist_table").empty();
$('<table id = "cyclist_results_table">').appendTo('#cyclist_table');
$.get("sam3.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist_results_table');
for (var j = 0; j <= cyclist_results_obtained.length; j++) {
$('<tr><td>' + cyclist_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist_results_obtained[j].name + '</td>' +
'<td>' + cyclist_results_obtained[j].gender + '</td>' +
'<td>' + cyclist_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist_results_table');
}
},'json');
$('</table>').appendTo('#cyclist_table');
}
function display_cyclist2_results_table() {
$("cyclist2_table").empty();
$('<table id = "cyclist2_results_table">').appendTo('#cyclist2_table');
$.get("sam4.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist2_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist2_results_table');
for (var j = 0; j <= cyclist2_results_obtained.length; j++) {
$('<tr><td>' + cyclist2_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist2_results_obtained[j].name + '</td>' +
'<td>' + cyclist2_results_obtained[j].gender + '</td>' +
'<td>' + cyclist2_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist2_results_table');
}
},'json');
$('</table>').appendTo('#cyclist2_table');
}
</script>
<title>sam.php</title>
</head>
<body>
<form name="form">
<table>
<tr><td><input name="Country_1" id="Country_1" value="GBR" type="text"></td></tr>
<tr><td><input name="Country_2" id="Country_2" value="USA" type="text"></td></tr>
<td><input id='toggle' type="button" value="Cyclist Comparison" onclick="call_everybody()"/></td></tr>
</table>
</form>
<div id = "toggle_table">
<div id="medal_table"></div>
<div id="cyclist_table"></div>
<div id="cyclist2_table"></div>
</div>
</body>
You need to add -
$('#results_table').remove();
Prior to -
$('<table id = "results_table">').appendTo('#medal_table');
I am trying to prevent the player from getting added again with the new value, rather I would like to just update the quantity..
HTML
<div class="playerTypeBlock" data-player-type-id="1" data-player-value="10.00">
<div class="heading">Ninja</div>
<div class="price">$10</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<div class="playerTypeBlock" data-player-type-id="2" data-player-value="20.25">
<div class="heading">Samurai</div>
<div class="price">$20.25</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<table class="teams" border="1">
<thead>
<tr>
<th>Players</th>
<th>Quantity</th>
</tr>
</thead>
<tbody class="totalPlayers"></tbody>
</table>
<div class="total">
<span>Total: $</span>
<span class="amount" id="totalvalue">0.00</span>
</div>
I tried using this when appending the table row, but not getting the desired result
JavaScript
var addToTeam = document.getElementsByClassName('addToTeam'),
parentElement = document.getElementsByClassName('playerTypeBlock'),
playerName = document.getElementsByClassName('heading'),
totalVal = document.getElementById('totalvalue'),
tableBody = document.querySelector('.totalPlayers');
var updatePlayers = function (evt) {
evt.preventDefault();
var amount = totalVal.innerHTML,
productId = this.parentElement.getAttribute('data-player-type-id'),
productPrice = this.parentElement.getAttribute('data-player-value'),
playerName = this.parentNode.querySelector('.heading').innerHTML,
updateTotal = parseFloat(amount) + parseFloat(productPrice);
var quantity = parseInt($(this).data('click'), 10) || 0;
quantity++;
$(this).data('click', quantity);
totalVal.innerHTML = Math.round(updateTotal * 100) / 100;
//adding the the table row here...
$('table .totalPlayers').append('<tr><td>' + playerName + '</td><td>' + quantity + ' </td></tr>');
};
for (var i = 0; i < addToTeam.length; i++) {
addToTeam[i].addEventListener('click', updatePlayers);
}
See Demo
Check quantity and append new row if it's 1 otherwise modify quantity cell:
if (quantity > 1) {
$('table .totalPlayers').find('#player-' + playerId + ' .quantity').text(quantity);
}
else {
$('table .totalPlayers').append('<tr id="player-' + playerId + '"><td>' + playerName + '</td><td class="quantity">' + quantity + ' </td></tr>');
}
Demo: http://jsfiddle.net/zx65uv8a/12/
This line the problem?
$('table .totalPlayers').append(
'<tr><td>' + playerName + '</td>' +
'<td>' + quantity + ' </td></tr>');
You are using append() so you'll always be adding and not replacing.
If you can add something unique to a class or id then you can replace it that way. i.e.
$('table .totalPlayers').append(
'<tr id="' + playerId + '">' +
'<td>' + playerName + '</td>' +
'<td class="quantity">' + quantity + ' </td></tr>');
Then to update
$('#' + playerId + ' .quantity').html(New value here);