Calculate quantity where textbox is a certain value - javascript

Edit
So many good answers and all of them work! Thanks a lot guys :) I wish I could mark all of them as solved!
----
Good day
Let's say I have these 2 text inputs:
<input type="text" id="plt_quantity_sum"/> <!-- this should calculate the "#quantity" where each "#uom_value" is "PLT" -->
<input type="text" id="crt_quantity_sum"/><!-- this should calculate the "#quantity" where each "#uom_value" is "CRT" -->
Let's assume the following scenario:
<table>
<tbody>
<tr>
<th>Item Name</th>
<th id="uom_value">UOM</th>
<th id="qty">Quantity</th>
</tr>
<tr>
<td>Item 1</td>
<td id="uom_value">PLT</td>
<td id="qty">5</td>
</tr>
<tr>
<td>Item 2</td>
<td class="uom_value">PLT</td>
<td id="qty">3</td>
</tr>
<tr>
<td>Item 3</td>
<td id="uom_value">CRT</td>
<td id="qty">2</td>
</tr>
<tr>
<td>Item 4</td>
<td id="uom_value">CRT</td>
<td id="qty">3</td>
</tr>
</tbody>
</table>
<input type="text" id="plt_quantity_sum" />
<input type="text" id="crt_quantity_sum" />
What needs to happen:
When the document loads, or via a button click; the quantity of "#plt_quantity_sum" and "#crt_quantity_sum" should be calculated based on their respective quantities and "UOM" values.
Some Javascript I had in mind which should clarify what exactly needs to happen:
$(document).ready(function(){
if (document.getElementById("#uom_value").value == "PLT"){
document.getElementById("#plt_quantity_sum").value == (sum of #qty);
}
else if (document.getElementById("#uom_value").value == "CRT"){
document.getElementById("#crt_quantity_sum").value == (sum of #qty);
}
});
Thanks for reading and I would greatly appreciate any help.

You just need declare two variables crtQtySum and pltQtySum for the two sums and initialize them to 0, then loop over the tds and check if it's crt or plt and updtae your variables accordingly:
$(document).ready(function() {
var crtQtySum = 0;
var pltQtySum = 0;
$(".uom_value").each(function() {
if ($(this).text() === "CRT") {
crtQtySum += parseInt($(this).next("td.qty").text());
} else if ($(this).text() === "PLT") {
pltQtySum += parseInt($(this).next("td.qty").text());
}
});
$("#plt_quantity_sum").val(pltQtySum);
$("#crt_quantity_sum").val(crtQtySum);
});
$(document).ready(function() {
var crtQtySum = 0;
var pltQtySum = 0;
$(".uom_value").each(function() {
if ($(this).text() === "CRT") {
crtQtySum += parseInt($(this).next("td.qty").text());
} else if ($(this).text() === "PLT") {
pltQtySum += parseInt($(this).next("td.qty").text());
}
});
$("#plt_quantity_sum").val(pltQtySum);
$("#crt_quantity_sum").val(crtQtySum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Item Name</th>
<th class="uom_value">UOM</th>
<th class="qty">Quantity</th>
</tr>
<tr>
<td>Item 1</td>
<td class="uom_value">PLT</td>
<td class="qty">5</td>
</tr>
<tr>
<td>Item 2</td>
<td class="uom_value">PLT</td>
<td class="qty">3</td>
</tr>
<tr>
<td>Item 3</td>
<td class="uom_value">CRT</td>
<td class="qty">2</td>
</tr>
<tr>
<td>Item 4</td>
<td class="uom_value">CRT</td>
<td class="qty">3</td>
</tr>
</tbody>
</table>
PLT:<input type="text" id="plt_quantity_sum" readonly/></br>
CRT:<input type="text" id="crt_quantity_sum" readonly/>
Note:
I used readonly attribute with the inputs, as they're just used to display the sums so they can't be modified, but we could just used a block element for that like div or span.

You can try this code. I ve didnt test it.
var plt_count = 0;
var crt_count = 0;
$(".uom_value").each(function() {
if($(this).html === 'PLT'){
plt_count += parseInt($(this).closest('.qty').html());
}
if($(this).html === 'CRT'){
crt_count += parseInt($(this).closest('.qty').html());
}
});
$("#plt_quantity_sum").val(plt_count);
$("#crt_quantity_sum").val(crt_count);

Apart from correcting the spelling mistakes that Hamza pointed out, I'd say you should basically iterate through the elements given its class name document.getElementsByClassName('.someclass') and then store and sum the value of each one of its siblings with class '.qty'.
Then you take that value and use it to populate the input you want.
Hope that helps ;)

This can be done using so many method, this is one of them :
$(document).ready(function(){
var sum_PLT = 0, sum_CRT = 0;
$('table > tbody > tr').each(function() {
tr = $(this)[0];
cells = tr.cells;
if(cells[0].textContent != "Item Name"){//To exclude the <th>
if(cells[1].textContent == "PLT")
sum_PLT += parseInt(cells[2].textContent);
else
sum_CRT += parseInt(cells[2].textContent);
}
});
$("#plt_quantity_sum").val(sum_PLT);
$("#crt_quantity_sum").val(sum_CRT);
});
This is a working jsFiddle.

You might want to try this code.
<script>
$(document).ready(function(){
var plt_qty = 0;
var crt_qty = 0;
$('.uom_value').each(function(){
if ($(this).text() === 'PLT' ) {
plt_qty = plt_qty + parseInt($(this).parent().find('.qty').text());
}else if ($(this).text() === 'CRT' ) {
crt_qty = crt_qty + parseInt($(this).parent().find('.qty').text());
}
});
$("#plt_quantity_sum").val(plt_qty);
$("#crt_quantity_sum").val(crt_qty);
});
</script>
Note : remove class uom_value in <th class="uom_value">UOM</th>.

Related

Toggle elements from classes with JS

I would like to show more information when someone click on show more buttons. The complication is that there are several buttons and informations to toggle with same className.
What am I doing wrong??
var element = document.querySelectorAll("btn");
for (var i = 0; i < button_length ; i++) {
element[i].addEventListener("click", function() {
alert("Button Clicked " + i);
element[i].classList.toggle("extrainfo");
};
}
td{border:solid 1px black;}
.btn, #btn_id{color:blue; text-decoration:underline; cursor:pointer;}
.extrainfo{
display:none
}
<table>
<tbody>
<tr class="info_group">
<td>Title 1</td>
<td class="btn">show more</td>
</tr>
<tr>
<td class="extrainfo" colspan="2">More info 1</td>
</tr>
</tbody>
<tbody>
<tr class="info_group">
<td>Title 2</td>
<td class="btn">show more</td>
</tr>
<tr>
<td class="extrainfo" colspan="2">More info 2</td>
</tr>
</tbody>
<tbody>
<tr class="info_group">
<td>Title 3</td>
<td class="btn">show more</td>
</tr>
<tr>
<td class="extrainfo" colspan="2">More info 3</td>
</tr>
</tbody>
</table>
to work you javaScript
var element = document.querySelectorAll("btn"); // need to be (".btn")
// you want it to be i < element.length; ? or there's a variable called button_length?
for (var i = 0; i < button_length ; i++) {
element[i].addEventListener("click", function() {
alert("Button Clicked " + i);
element[i].classList.toggle("extrainfo");
}; // missing a Parenthesis need to be this }); not this };
}
I'm still not sure about the functionality, but see the code below if that's what you're looking for.
var element = document.querySelectorAll(".btn");
var extraInfo = document.querySelectorAll(".extrainfo");
for (let i = 0; i < element.length; i++) {
element[i].addEventListener("click" , function() {
extraInfo[i].classList.toggle("extrainfo");
});
}
hereJSFiddle you can play around with the code

Sum table values based on grouping

I have the following table:
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
I need a way to add/sum all values grouped by category, ie: add/sum all values in cat1, then add/sum all values in cat2. For each group I will do something with the total.
So I was hoping for something like:
for each unique category:
sum values in category
do something with this category total
For cat1 the total would be 123 + 486. Cat2 would just be 356. And so on if there were more categories.
I would prefer a purely javascript solution, but JQuery will do if that's not possible.
If I understand you correctly, you do a repeat of each td:first-child (The category cell).
Create a total object. You can check if the category is exist in it for each cell. If so, add current value to the stored value. If not, insert new property to it.
Like this:
var total = {};
[].forEach.call(document.querySelectorAll('td:first-child'), function(td) {
var cat = td.getAttribute('class'),
val = parseInt(td.nextElementSibling.innerHTML);
if (total[cat]) {
total[cat] += val;
}
else {
total[cat] = val;
}
});
console.log(total);
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
Here's a simple approach using only javascript
//grab data
var allTR = document.getElementsByTagName('TR');
var result = {};
//cycle table rows
for(var i=0;i<allTR.length;i+2){
//read class and value object data
var class = allTR[i].getAttribute('class');
var value = allTR[i+1].innerText;
//check if exists and add, or just add
if(result[class])
result[class] += parseInt(value);
else
result[class] = parseInt(value);
}
You have to use getElementsByTagName("td"); to get all the <td> collection and then you need to loop through them to fetch their innerText property which later can be summed up to get the summation.
Here is the working Fiddle : https://jsfiddle.net/ftordw4L/1/
HTML
<table id="tbl1">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
<tr>
<td class="total"><b>Total</b></td>
<td class="totalValue"></td>
</tr>
</table>
Javascript
var tds=document.getElementsByTagName("td");
var total=0;
for (var i = 0; i<tds.length; i++) {
if (tds[i].className == "value") {
if(total==0) {
total = parseInt(tds[i].innerText);
} else {
total = total + parseInt(tds[i].innerText);
}
}
}
document.getElementsByClassName('totalValue')[0].innerHTML = total;
Hope this helps!.
here is a solution with jQuery :) if you are interested. it's pretty straightforward
var sumCat1 = 0;
var sumCat2 = 0;
$(".cat1 + .value").each(function(){
sumCat1 += parseInt($(this).text());
})
$(".cat2 + .value").each(function(){
sumCat2 += parseInt($(this).text());
})
console.log(sumCat1)
console.log(sumCat2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
A simple approach in JQuery...
var obj = {};
$('tr').each(function() {
$this = $(this)
if ($this.length) {
var cat = $(this).find("td").first().html();
var val = $(this).find("td").last().html();
if (cat) {
if (!obj[cat]) {
obj[cat] = parseInt(val);
} else {
obj[cat] += parseInt(val);
}
}
}
})
console.log(obj)

Highlight table cell based on vertical and horizontal headers

I have a "football squares" game going, and I would like to highlight cells of the winners based on the top and side headers.
Now, I know they're not really headers but they serve the same purpose.
My table is located at this jfiddle: https://jsfiddle.net/8ybtntqg/
What I want to do is this:
Let's say the winner would be whoever is in the cell that lines up with TeamA - 2 and TeamZ - 9. That would be Mitch. I want to highlight Mitch's cell. How would I do this with Javascript or Jquery? I know how to do it if I was just looking for the word "Mitch", but I want to automatically do it, based on the numbers of TeamA and TeamZ.
I have this so far, but of course that only highlights the name but it's the only place I knew to start:
$('#table_id td').each(function() {
if ($(this).text() == 'Mitch') {
$(this).closest('td').css('background-color', '#f00');
}
});
You can get the index of the column and row using jQuery's filter() method.
That will give you direct access to the cell like so:
$('tr').eq(row).find('td').eq(col).css('background-color', '#f00');
Snippet:
function highlight(teamA, teamZ) {
var col, row;
col = $('#table_id td').filter(function() { //return column of teamA
return $(this).html() === teamA.replace(' - ', '<br>');
}).index();
row = $('#table_id tr').filter(function() { ////return row of teamZ
return $(this).html().indexOf(teamZ.replace(' - ', '<br>')) > -1;
}).index();
$('tr').eq(row).find('td').eq(col).css('background-color', '#f00');
}
highlight('TeamA - 2', 'TeamZ - 9');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="table_id">
<tr>
<td>Squares</td>
<td>TeamA<br>1</td>
<td>TeamA<br>2</td>
<td>TeamA<br>3</td>
<td>TeamA<br>4</td>
<td>TeamA<br>5</td>
<td>TeamA<br>6</td>
<td>TeamA<br>7</td>
<td>TeamA<br>8</td>
<td>TeamA<br>9</td>
<td>TeamA<br>0</td>
</tr>
<tr>
<td>TeamZ<br>3</td>
<td bgcolor="#89ff89">Mark</td>
<td bgcolor="#89ff89">John</td>
</tr>
<tr>
<td>TeamZ<br>5</td>
<td bgcolor="#89ff89">Mike</td>
<td bgcolor="#89ff89">Earl</td>
</tr>
<tr>
<td>TeamZ<br>8</td>
<td bgcolor="#89ff89">Morris</td>
<td bgcolor="#89ff89">Brice</td>
</tr>
<tr>
<td>TeamZ<br>7</td>
<td bgcolor="#89ff89">Taylor</td>
<td bgcolor="#89ff89">Evan</td>
</tr>
<tr>
<td>TeamZ<br>9</td>
<td bgcolor="#89ff89">Mandy</td>
<td bgcolor="#89ff89">Mitch</td>
</tr>
<tr>
<td>TeamZ<br>2</td>
<td bgcolor="#89ff89">Tony</td>
<td bgcolor="#89ff89">Jennifer</td>
</tr>
<tr>
<td>TeamZ<br>1</td>
<td bgcolor="#89ff89">Kristen</td>
<td bgcolor="#89ff89">Hector</td>
</tr>
<tr>
<td>TeamZ<br>4</td>
<td bgcolor="#89ff89">Gabby</td>
<td bgcolor="#89ff89">David</td>
</tr>
<tr>
<td>TeamZ<br>6</td>
<td bgcolor="#89ff89">George</td>
<td bgcolor="#89ff89">Steffanie</td>
</tr>
<tr>
<td>TeamZ<br>0</td>
<td bgcolor="#89ff89">Breck</td>
<td bgcolor="#89ff89">Terry</td>
</tr>
</table>
You can iterate over all the table elements to find the matching values, then use CSS selectors to highlight the matched field. Something like this will work:
winningAScore = 2;
winningZScore = 9;
//get top row
counter = 0;
$('#table_id tr:first-child td').each(function() {
var strOut = $(this).html().replace(/Team[A-z]<br>/g,'');
if(!isNaN(strOut) && strOut == winningAScore) {
posnX = counter;
}
counter++;
})
//get first column row
counter = 0;
$('#table_id tr td:first-child').each(function() {
var strOut = $(this).html().replace(/Team[A-z]<br>/g,'');
if(!isNaN(strOut) && strOut == winningZScore) {
posnY = counter;
}
counter++;
})
$('tr:eq('+posnY+') td:eq('+posnX+')').css('background-color', 'red');
You can see it working in this JS Fiddle: https://jsfiddle.net/igor_9000/8ybtntqg/1/
You can do index based detect and selection in jQuery like so: $('tr:eq(2) td:eq(1)').css('background-color', 'red');
Example: http://codepen.io/anon/pen/EPLNvB

How To Sum All Table Rows td (TotalPrice) using td id Jquery

I am adding values to table like:
Item,Quantity,Price,TotalPrice
Now there are multiple rows: How can i sum TotalPrice of all to get GrandTotal using Jquery.
Code:
$("#Product").append(" <tr><td id='clientname'>" +ClientName+ "</td> <td id='item'>"+ItemName+"</td> <td id='quantity'>"+Quantity+"</td> <td id='price'>"+Price+"</td> <td id='totalprice'>"+TotalPrice+"</td> <td> <a onClick='deleteRow(this);'>Delete</a> </td> </tr>");
Its possible when i insert new row data its show grand total in textbox/label,Like:
function TotalPriceCalc()
{
var lblTotalPrice = document.getElementById('lblTotalPrice');
lblTotalPrice.value = sum;
}
Here's an example that will sum whatever column index you provide.
$(function() {
$("#subtotal").html(sumColumn(4));
$("#total").html(sumColumn(5));
});
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="border-spacing: 10px;">
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>12</td>
<td>34</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>56</td>
<td>78</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>90</td>
<td>12</td>
</tr>
<tr>
<td colspan="3">Totals</td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</table>
After you use class= instead of id= .Cause ID MUST be unique. you need to loop through each row and find totalPrice
$(document).ready(function(){
var TotalValue = 0;
$("#Product tr").each(function(){
TotalValue += parseFloat($(this).find('.totalprice').text());
});
alert(TotalValue);
});
While you tagged Jquery .. This is a Jquery solution so please be sure to include Jquery
You should use classes, not IDs, to name repeated elements. So it should be:
...<td class="totalprice">'+TotalPrice+'</td>...
Then you can do
function TotalPriceCalc() {
var total = 0;
$(".totalprice").each(function() {
total += parseFloat($(this).text());
});
$("#lblTotalPrice").val(total);
}
Have look, this is our table
<table class="table table-bordered">
<thead>
<tr>
<th>1</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="loop">50</td>
</tr>
<tr>
<td>1</td>
<td id="loop">60</td>
</tr>
<tr>
<td>1</td>
<td id="loop">70</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="text-right">Total</td>
<td></td>
</tr>
</tbody>
And this is loop to have sum of price
$(function() {
var TotalValue = 0;
$("tr #loop").each(function(index,value){
currentRow = parseFloat($(this).text());
TotalValue += currentRow
});
console.log(TotalValue);
});

jqQuery find cell value, if exists change cell, if not add new row

Any help would be greatly appreciated.
What I'm trying to achieve is when a number/text in input into the code box it searches the table, if found increments quantity by one, if not found adds a new row counting the no column by one.
I already a some basic jQuery code.
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Release"/>
<table> <thead>
<tr>
<th>No</th>
<th>Code</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>4444</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>5555</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>6666</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>7777</td>
<td>1</td>
</tr>
</tbody>
</table>
edit: my code.
$(document).ready(function() {
$("#btnSubmit").click(function() {
var code = $("input#code").val()
var table = $("table tbody");
table.find('tr').each(function(i) {
no = $(this).find('td').eq(0).text(),
productId = $(this).find('td').eq(1).text(),
Quantity = $(this).find('td').eq(2).text();
if (productId == code) { //see if product is in table
Quantity = +Quantity + +Quantity; // increase qty
alert('found' + Quantity); 
} else {
// Add new row
alert('not found');
}
});
});
});
I put together a JSFiddle for you, and copied the JS code here. I tried to make it as beginner friendly as possible...
$("#btnSubmit").on("click", function(){
numRows = $("tr").length;
for(var i=1 ; i<numRows ; i++){
var code = $("tr:nth-child(" + i + ") td:nth-child(2)").html();
var qty = $("tr:nth-child(" + i + ") td:nth-child(3)").html();
if(code == $("#code").val()){
$("tr:nth-child(" + i + ") td:nth-child(3)").html(parseInt(qty) + 1);
return true;
}
}
$("tbody").append("<tr><td>" + numRows + "</td><td>" + $("#code").val() + "</td><td>1</td></tr>");
return true;
});
I have created a sample code using jQuery. It took me like 10 minutes to figure out what you are trying to achive but I hope I understood you quite well:
HTML Side:
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Release"/>
<table> <thead>
<tr>
<th>No</th>
<th>Code</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>4444</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>5555</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>6666</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>7777</td>
<td>1</td>
</tr>
</tbody>
</table>
and our JavaScript:
$(document).ready(function() {
var found = false;
$("input#btnSubmit").on("click", function() {
var search_val = $("input#code").val();
$("tr").each(function() {
var obj = $(this);
obj.find("td").each(function() {
if(parseInt($(this).html()) == parseInt(search_val))
{
obj.find("td:nth-of-type(3)").html(parseInt(obj.find("td:nth-of-type(3)").html()) + 1);
found = true;
}
});
})
if(found == false)
{
$("table").append("<tr><td>"+($("tr").length)+"</td><td>"+search_val+"</td><td>1</td></tr>");
}
found = false;
});
});
Here's JSFiddle: http://jsfiddle.net/f17gudfw/4/

Categories