automatically multiply two values to give a total jquery - javascript

I have a jQuery question an was wondering if anyone could help me out.
I have an html table with information in it specifically for stones. I have a price per carat and a price per stone at the end of the table. I wish to have the price per carat multiply by the weight to give the price per stone. I also have a markup box that i have created in which the user inputs a number which is then regarded as a % and is automatically added to the price per carat and price per stone. here is what i have so far:
Here is the jquery
jQuery(document).ready(function () {
jQuery("#markup").keyup(multInputs);
function multInputs() {
var $inmult = jQuery(this).val();
jQuery("tr").each(function () {
var $val1 = jQuery('.price .amount', this).text().substring(1);
var $mult = $inmult / 100;
$mult += 1;
var $total = $val1 * $mult;
jQuery('.adjprice .amount', this).text("$" + $total.toFixed(2));
$val1 = jQuery('.org_ct', this).text();
$mult = $inmult / 100;
$mult += 1;
$total = $val1 * $mult;
jQuery('.adj_ct', this).text($total.toFixed(2));
});
}
});
Here is the HTML
<span class="markup">Adjust Price: <input name="markup" id="markup"> % </span>
<table id="myTable" class="tablesorter-blackice">
<thead>
<tr>
<th>Sku#</th>
<th>Availability</th>
<th>Cert #</th>
<th>Shape</th>
<th>Weight</th>
<th>Colour</th>
<th>Clarity</th>
<th>Cut</th>
<th>[MM]</th>
<th style="display:none" class="header">US$/ct</th>
<th class="header">US$/ct</th>
<!--<th>CDN$/ct</th>-->
<th style="display:none" class="header">Hidden Orig Price</th>
<th class="header">US$/St</th>
</tr>
</thead>
<tbody>
<tr>
<td>rerew</td>
<td>erewr</td>
<td>wrer</td>
<td>ewrer</td>
<td>erwer</td>
<td>ere</td>
<td>ewr</td>
<td>ewrew</td>
<td>wreew</td>
<td class="org_ct" style="display:none">
<td class="adj_ct">1234</td>
</td>
<td class="price" style="display:none">
<td class="adjprice">
<span class="amount"></span>
</td>
</td>
</tr>
</tbody>
</table>
The number is not automatically being multiplied to give me a price per stone. also the markup is not working either I really appreciate the help. THANKS!

If I understand your question correctly, this should do what you need. Note that I un-hid some of the columns to make it easier to work with, you'll need to hide them again.
jQuery(document).ready(function () {
function iDoMathsGood() {
$('.amount').map(function () {
// get all of the elements we'll need to manipulate
var row = $(this).parent().parent();
var originalTtl = row.find('.price');
var adjusted = row.find('.adj_ct');
// get the numbers we'll need and do some math
var cts = Number(row.find('.weight').html());
var origPPCT = Number(row.find('.org_ct').html()) * 1000;
var markupPrct = Number($('#markup').val()) / 100;
var markedupCost = (origPPCT * markupPrct) + origPPCT;
// do a little more math them set the results
adjusted.html((markedupCost / 1000).toFixed(2));
originalTtl.html(((origPPCT * cts) / 1000).toFixed(2));
return $(this).html(((markedupCost * cts) / 1000).toFixed(2));
});
}
iDoMathsGood();
$('#markup').keyup(function(){
iDoMathsGood();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="markup">Adjust Price: <input name="markup" id="markup" value="10"/> % </span>
<table id="myTable" class="tablesorter-blackice" border="1">
<thead>
<tr>
<th>Sku#</th>
<th>Availability</th>
<th>Cert #</th>
<th>Shape</th>
<th>Weight</th>
<th>Colour</th>
<th>Clarity</th>
<th>Cut</th>
<th>[MM]</th>
<th class="header">US$/ct</th>
<th class="header">US$/ct</th>
<th class="header">Hidden Orig Price</th>
<th class="header">US$/St</th>
</tr>
</thead>
<tbody>
<tr>
<td>rerew</td>
<td>erewr</td>
<td>ewrer</td>
<td>erwer</td>
<td class="weight">12</td>
<td>ewr</td>
<td>ewr</td>
<td>ewrew</td>
<td>wreew</td>
<td class="org_ct">42.50</td>
<td class="adj_ct"></td>
<td class="price"></td>
<td class="adjprice"> <span class="amount"></span>
</td>
</tr>
<tr>
<td>rerew</td>
<td>erewr</td>
<td>ewrer</td>
<td>erwer</td>
<td class="weight">6</td>
<td>ewr</td>
<td>ewr</td>
<td>ewrew</td>
<td>wreew</td>
<td class="org_ct">32.75</td>
<td class="adj_ct"></td>
<td class="price"></td>
<td class="adjprice"> <span class="amount"></span>
</td>
</tr>
</tbody>
</table>

To begin with, you're calling the multInputs function improperly. Don't forget the () when calling a function (or other method).
jQuery("#markup").keyup(multInputs);
should be
jQuery("#markup").keyup(multInputs());
From there, you've got a few other errors (to begin with):
var $inmult = $(this).val();, you're calling this from within the function but without actually having a "this" to be referred to. If you move this within the "each" function, then you'll have a "this" to refer to.
Of course, make sure you've linked to JQuery! :)
I would also add a class to the weight to make it easy to refer to
I'm not going to debug the whole thing but this should give you a start
$(document).ready(function () {
$("#markup").keyup(multInputs());
function multInputs() {
$("tr").each(function () {
var $inmult = $(this).find('td.weight' ).text();
var $val1 = $('.price .amount', this).text().substring(1);
var $mult = $inmult / 100;
$mult += 1;
var $total = $val1 * $mult;
$('.adjprice .amount', this).text("$" + $total.toFixed(2));
$val1 = $('.org_ct', this).text();
$mult = $inmult / 100;
$mult += 1;
$total = $val1 * $mult;
$('.adj_ct', this).text($total.toFixed(2));
});
}
});

Related

Find().Each() calculation in table cell

Not really sure what I'm missing. I need to run some calculations in a table cell. I have several tables on the page. Each table has its own ID. So I only need to run the calculation for one specific table at the time (per the ID).
let calculateDiscountFromEffective = function(id){
console.log(' BUTTON PRESSED ' + id);
$(".tableTab2").find("tr").each(function(){
var tableID = $(this).closest('tr').attr('id');
if(tableID == id) {
let targetDisc = calculateRequiredDiscountRate($(this));
$(this).closest("tr").find(".discountRatePercent").val((targetDisc * 100.0).toFixed(2));
calculateDiscount($(this));
}
});
}
let calculateRequiredDiscountRate = function($tr){
let daysOutstanding = $tr.find(".daysOutstanding").asNumber();
let maturityBuffer = $tr.find(".maturityBuffer").asNumber();
let effectiveRate = $("input[id$='txtEffectiveRate']").asNumber();
let targetDisc = (effectiveRate * daysOutstanding / 100.0)/((daysOutstanding + maturityBuffer) * (1.0 - effectiveRate * daysOutstanding / 360.0 / 100.0));
return targetDisc;
}
Problem:
The first "IF", where I compare tableID and id, returns only the first row and stops. When I remove the "IF", it will be processing the calculation for all rows in all tables on the page. How do I make it work for a specific table?
Here is a portion of my table:
<table class="table tableTab2" id="{!oppWrapper.oppSchoolName}">
<thead>
<tr id="{!oppWrapper.oppSchoolName}">
<th class="col1">{!$Label.FE_P2_Receivable_Name}</th>
<th class="col2">{!$Label.FE_P2_Purchase_Date}</th>
Here is my button:
<button class="btn btn-tertiary" id="{!oppWrapper.oppSchoolName}" onClick="calculateDiscountFromEffective(id);return false;">Calc. rates</button>
Thanks in advance
The id has to added into the as well as the . With that said here is the modified table:
<table class="table tableTab2" id="{!oppWrapper.oppSchoolName}">
<thead>
<tr id="{!oppWrapper.oppSchoolName}">
<th class="col1">{!$Label.FE_P2_Receivable_Name}</th>
<th class="col2">{!$Label.FE_P2_Purchase_Date}</th>
...
</tr>
</thead>
<tbody>
<tr id="{!oppWrapper.oppSchoolName}">
<td style="line-height: 30px !important"> ...</td>
<td style="line-height: 30px !important"> ...</td>
...

How can I change my code into clickable row from input checkbox row in jquery?

I have a table and the data in this table is from database. I want to click this row and transfer it to other table. I can transfer this row using input checkbox. I'd realize that it will be easy and convenient to transfer the rows by just clicking it without checkbox. I have a hard time converting it to a clickable instead of checkbox.
I tried using this code
$(document).ready(function() {
$( "#table1 tbody tr" ).on( "click", function( event ) {
var product = $(this).attr('data-product');
var price = $(this).attr('data-price');
var barcode = $(this).attr('data-barcode');
var unit = $(this).attr('data-unt');
var qty = prompt("Enter number of items",1);
var total = qty*price;
$('#tableData').append("<tr><td>"+barcode+"</td><td>"+product+"</td><td>₱"+price+"</td><td>"+unit+"</td><td>"+qty+"</td><td>₱"+total+"</td><tr>");});
This is my jquery that I wanted to convert into clickable code.
function add(){
$('input:checked[name=tab1]').each(function() {
var product = $(this).attr('data-product');
var price = $(this).attr('data-price');
var barcode = $(this).attr('data-barcode');
var unit = $(this).attr('data-unt');
var qty = prompt("Enter number of items",1);
var total = qty*price;
$('#tableData').append("<tr><td>"+barcode+"</td><td>"+product+"</td><td>₱"+price+"</td><td>"+unit+"</td><td>"+qty+"</td><td>₱"+total+"</td><tr>"); });}
My PHP code.
<?php
include('server/connection.php');
if (isset($_POST['products'])){
$name = mysqli_real_escape_string($db,$_POST['products']);
$num = 1;
$show = "SELECT * FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
$total = $num*$row['sell_price'];
echo "<tr id='sas'><td>".$row['id']."</td><td>".$row['product_name']."</td>";
echo "<td>₱".$row['sell_price']."</td>";
echo "<td>".$row['unit']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td><input type='checkbox' name='tab1' data-barcode='".$row['id']."' data-product='".$row['product_name']."' data-price='".$row['sell_price']."' data-unt='".$row['unit']."' data-qty='".$num."' data-total='".$total."'/></td></tr>";
}
}
else{
echo "<td></td><td>No Products found!</td><td></td>";
}
}
My Table
<table id="table1">
<thead>
<tr>
<td>Barcode</td>
<td>Product Name</td>
<td>Price</td>
<td>Unit</td>
<td>Stocks</td>
<td>Action</td>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
<table id="table2">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
I expect by just clicking the row it will automatically transfer to the table2 with a dialog box using prompt that will ask for quantity of a product then it will be printed to the second table along with the entire row.
This is my UI with css.
You are on the right way, just fix JS selectors using $(this) and formating the price...
$("#table1 .js-add").on("click", function() {
var target = $(this);
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
var qty = prompt("Enter number of items", 1);
var total = qty * price;
$('#tableData').append("<tr><td>" + barcode + "</td><td>" + product + "</td><td>" + price + "</td><td>" + unit + "</td><td>" + qty + "</td><td>" + total.toFixed(2) + "</td><tr>");
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<table id="table1" class="table">
<thead>
<tr>
<th>Barcode</th>
<th>Product Name</th>
<th>Price</th>
<th>Unit</th>
<th>Stocks</th>
<th>Action</th>
</tr>
</thead>
<tbody id="products">
<tr>
<td>123412</td>
<td>Test</td>
<td>12.99</td>
<td>1</td>
<td>10</td>
<td>
<input name='tab1' type="checkbox" class='js-add' data-barcode="123412" data-product="Test" data-price="12.99" data-unt="1"/>
</td>
</tr>
</tbody>
</table>
<br>
<table id="table2" class="table">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
You need to use event.target instead of this in the function.
$(document).ready(function() {
$( "#table1 tbody tr" ).on( "click", function( event ) {
var target = event.target;
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
var qty = prompt("Enter number of items",1);
var total = qty*price;
$('#tableData').append("<tr><td>"+barcode+"</td><td>"+product+"</td><td>₱"+price+"</td><td>"+unit+"</td><td>"+qty+"</td><td>₱"+total+"</td><tr>");});
On tr click event, you are using data-product and other selectors. data-product is not defined for tr. You have to add data-product attribute for each row. You can refer this - JQuery: Find (the index of) a row with a specific data attribute value

td element not parsed to int

I have a table with id #tab1.
For each row, I want to calculate the value of column Points / Matches and to put it in the column Coeficiency, but my code doesn't work.
The numbers aren't parsed to int. I would always like to know if
elem[4].innerHTML(z); is ok to set coeficiency.
Average();
function Average() {
var table = document.getElementById('tab1'),
rows = table.getElementsByTagName('tbody')[1].getElementsByTagName('tr');
//console.log(rows.length);
for (var i = 0; i < rows.length; i++) {
elem = rows[i].getElementsByClassName("columns");
var x = parseInt(elem[2]);
var y = parseInt(elem[3]);
// console.log(x+y," ");
console.log(x, " ", y);
var z = y / x;
elem[4].innerHTML(z);
}
<div id="mytable">
<table id="tab1">
<tr class="rows">
<th class="columns">#</th>
<th class="columns">Team</th>
<th class="columns">Matches</th>
<th class="columns">Points</th>
<th class="columns">Coeficiency</th>
</tr>
<tbody>
<tr class="rows">
<td class="columns">1</td>
<td class="columns">Baetasii</td>
<td class="columns">3</td>
<td class="columns">9</td>
<td class="columns">100%</td>
</tr>
<tr class="rows">
<td class="columns">2</td>
<td class="columns">Carcotasii</td>
<td class="columns">2</td>
<td class="columns">5</td>
<td class="columns">100%</td>
</tr>
</tbody>
</table>
</div>
Okay, so a few pointers having looked over your code, first of all innerHTML is not a function, it's a simple property, you can just reassign it, however, I suggest using textContent due to the fact that using innerHTML, you can allow for XSS to occur.
I mean I know XSS probably isn't an issue in this specific scenario, however I thought it my be of value mentioning that.
Also, as I mentioned in the comments above, using parseInt, you need to pass it a string rather than an object which is what you were originally doing. Using functions such as getElementsByClassName or querySelectorAll, you'll have an array-like object, such as a HTMLCollection which contains a number of objects, usually Elements or Nodes.
Average();
function Average() {
var table = document.getElementById('tab1'),
rows = table.getElementsByTagName('tbody')[1].getElementsByTagName('tr');
//console.log(rows.length);
for (var i = 0; i < rows.length; i++) {
elem = rows[i].getElementsByClassName("columns");
var x = parseInt(elem[2].textContent);
var y = parseInt(elem[3].textContent);
// console.log(x+y," ");
console.log(x, " ", y);
var z = y / x;
elem[4].textContent = z;
}
}
<div id="mytable">
<table id="tab1">
<tr class="rows">
<th class="columns">#</th>
<th class="columns">Team</th>
<th class="columns">Matches</th>
<th class="columns">Points</th>
<th class="columns">Coeficiency</th>
</tr>
<tbody>
<tr class="rows">
<td class="columns">1</td>
<td class="columns">Baetasii</td>
<td class="columns">3</td>
<td class="columns">9</td>
<td class="columns">100%</td>
</tr>
<tr class="rows">
<td class="columns">2</td>
<td class="columns">Carcotasii</td>
<td class="columns">2</td>
<td class="columns">5</td>
<td class="columns">100%</td>
</tr>
</tbody>
</table>
</div>
Edit
I thought I'd also include a neater version, it does near enough the same logic stuff, it's more or less just more modern JavaScript syntax, using a more 'functional-style'. Originally I basically copied the exact same style that you provided for the sake of simplicity, but I thought that there's a few issues with that. An example being how you've used a capital letter for the Average, personally I only use a capital letter at the start of a name if it's a class, this is a personal choice however, feel free to disagree or stick to what you know!
I personally prefer using more modern syntax as personally I think is easier to read, it's more clear and concise, generally it looks like less code to read through.
// States if an array like object is empty or not.
const isEmpty = a => a.length > 0;
// Returns the text content of a html object.
const txt = td => td == null ? null : td.textContent;
// Simply updates the UI.
const render = tds => v => tds[4].textContent = parseFloat(v).toFixed(2);
// Works out whether or not to fire update or do nothing.
const compute = tds => isEmpty(tds) ? render(tds)(txt(tds[3]) / txt(tds[2])) : null;
// Gets the average for each tr.
const avg = trs => trs.forEach(tr => compute(tr.querySelectorAll("td")));
// Fire the avg function.
const update = () => avg(document.querySelectorAll("#tab1 tbody tr"));
// Render tr tag.
const renderTr = i => n => m => p => `<tr>
<td>${i}</td><td>${n}</td><td>${m}</td><td>${p}</td><td></td>
</tr>`;
// Add a table row.
const append = () => {
const tbl = document.getElementById("tab1");
const i = document.querySelectorAll("#tab1 tbody tr").length,
n = '_____',
m = Math.floor(Math.random() * 10) + 1,
p = Math.floor(Math.random() * 10) + 1;
// Safe-ish because what's being entered is controlled 100%.
// But generally try not to use innerHTML.
tbl.innerHTML += renderTr(i)(n)(m)(p);
update();
};
// Allow for auto add.
document.getElementById("add").onclick = append;
update(); // Initial run.
<div id="mytable">
<table id="tab1">
<tr class="rows">
<th class="columns">#</th>
<th class="columns">Team</th>
<th class="columns">Matches</th>
<th class="columns">Points</th>
<th class="columns">Coeficiency</th>
</tr>
<tbody>
<tr class="rows">
<td class="columns">1</td>
<td class="columns">Baetasii</td>
<td class="columns">3</td>
<td class="columns">9</td>
<td class="columns">100%</td>
</tr>
<tr class="rows">
<td class="columns">2</td>
<td class="columns">Carcotasii</td>
<td class="columns">2</td>
<td class="columns">5</td>
<td class="columns">100%</td>
</tr>
</tbody>
</table>
</div>
<button id="add">Add Row</button>
Using Object#values Array#forEach #getElementsByTagName
The main issue is that you needed to retrieve the text value with innerText.
You also don't need the redundant class names.
const table = document.getElementById("table");
const rows = table.querySelectorAll("tbody > tr");
Object.values(rows).forEach(row => {
const tds = row.getElementsByTagName('td');
if (tds.length === 5) {
const x = parseInt(tds[2].innerText),
y = parseInt(tds[3].innerText);
const z = y / x;
tds[4].innerText = `${z}`;
}
});
<table id="table">
<tr>
<th>#</th>
<th>Team</th>
<th>Matches</th>
<th>Points</th>
<th>Coeficiency</th>
</tr>
<tbody>
<tr>
<td>1</td>
<td>Baetasii</td>
<td>3</td>
<td>9</td>
<td>100%</td>
</tr>
<tr>
<td>2</td>
<td>Carcotasii</td>
<td>2</td>
<td>5</td>
<td>100%</td>
</tr>
</tbody>
</table>
getElementsByClassName returns an array-like object of all child elements which have all of the given class names.
Since we have a collection of DOM elements, elem[2] it's a DOM element and you should access its textContent property.
Also, you're using innerHTML property in a wrong way. Just replace
elem[4].innerHTML(z);
to
elem[4].innerHTML = z;
Average();
function Average() {
var table = document.getElementById('tab1'),
rows = table.getElementsByTagName('tbody')[1].getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
elem = rows[i].getElementsByClassName("columns");
var x = parseInt(elem[2].textContent);
var y = parseInt(elem[3].textContent);
console.log(x, " ", y);
var z = y / x;
elem[4].innerHTML = z;
}
}
<div id="mytable">
<table id="tab1">
<tr class="rows">
<th class="columns">#</th>
<th class="columns">Team</th>
<th class="columns">Matches</ht>
<th class="columns">Points</th>
<th class="columns">Coeficiency</th>
<tbody>
<tr class="rows">
<td class="columns">1</td>
<td class="columns">Baetasii</td>
<td class="columns">3</td>
<td class="columns">9</td>
<td class="columns">100%</td>
</tr>
<tr class="rows">
<td class="columns">2</td>
<td class="columns">Carcotasii</td>
<td class="columns">2</td>
<td class="columns">5</td>
<td class="columns">100%</td>
</tr>
</tbody>
</table>
</div>

jquery dynamic for each loop issue

I have a table that has several tables in it for multiple users. These users can increase or decrease overtime, so I am trying to make it as dynamic as possible. I will attach two sample tables so you get the idea.
<div class="timecard">
<h3>tommytest</h3>
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<tbody>
<tr class="display_row odd">
<td align="left" class="job_code" style="color:#000099">2400-Orchard</td>
<td align="right">9:47am</td>
<td align="right">5/19/2014</td>
<td align="right" class="hrs">01:00</td>
</tr>
<tr class="display_odd row">
<td align="left" class="job_code" style="color:#000099">1200-Duffy's</td>
<td align="right">12:37am</td>
<td align="right">5/17/2014</td>
<td align="right" class="hrs">2:00</td>
</tr>
</tbody>
</table>
</div>
<div class="timecard">
<h3>testtest</h3>
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<tbody>
<tr class="display_row odd">
<td align="left" class="job_code" style="color:#000099">2400-Orchard</td>
<td align="right">9:47am</td>
<td align="right">5/19/2014</td>
<td align="right" class="hrs">01:00</td>
</tr>
<tr class="display_odd row">
<td align="left" class="job_code" style="color:#000099">1200-Duffy's</td>
<td align="right">12:37am</td>
<td align="right">5/17/2014</td>
<td align="right" class="hrs">2:00</td>
</tr>
</tbody>
</table>
</div>
<div id="total"></div>
I then have a jQuery script run through the table and then calculate the total of each individual job_code and display it underneath the table so that it looks like this:
job_code 1 = 2 hours
job_code 2 = 4 hours
I am having trouble making my below javascript calculate the first table, display the results, then move on to the next table and do the same thing. So on and so forth.
$(document).ready(function () {
var timeString = $(this).next('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;
var temp = [];
$('.job_code').each(function (index, element) {
var text = $(this).text();
if (text != 'Out') {
temp.push(text);
}
});
// remove duplicates
var job_code = [];
$.each(temp, function (index, element) {
if ($.inArray(element, job_code) === -1) job_code.push(element);
});
var sum = {};
$.each(job_code, function (index, element) {
var total = 0;
$('.job_code:contains(' + element + ')').each(function (key, value) {
var timeString = $(this).siblings('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;
sum[index] = {
'job_code': element,
'total': total
};
});
});
console.log(sum);
$.each(sum, function (index, element) {
$('#total').append('<p>Total for ' + element.job_code + ': ' + element.total + '</p>');
});
});
Any advice would be greatly appreciated as I am just starting to use javascript and am quickly reaching the end of my capabilities. Here is a link to a sample JSfiddle
Thanks in advance
First of all why not to make any calculations before formatting and layout generation? I would be much easier.
Anyway if you want to iterate tables then iterate some data in it, try to use something like this:
$('.timecard_list').each(function() {
$(this).find('.job_code').each(function() {
...
});
});

Change cell value depending on input of another cell with JavaScript

thanks to peoples help on here I have nearly finished what I set out to do yesterday/
I have included a fiddle here http://jsfiddle.net/uzW5e/
I would like it that when someone enters a value greater than 85 in the column headed Percentage Grade (class percGrade) the value 1 is put in the column headed Pass Level (class passLevel) but it isn't working?
<table align="center">
<tr>
<th>
Module
</th>
<th>
Percentage Grade
</th>
<th>
Credits
</th>
<th>
Pass Level
</th>
<th>
WGC
</th>
</tr>
<tr class="multRow">
<td>
<input name="module" />
</td>
<td>
<input name="percentageGrade" class="percGrade" />
</td>
<td>
<input name="credits" class="credits"/>
</td>
<td>
<input name="passLevel" class="passLevel"/>
</td>
<td>
<span class="multTotal">0.00</span>
</td>
</tr>
<tr>
<td colspan="5" align="right">
Total <span id="grandTotal">0</span>
</td>
<script>
$(document).ready(function () {
$(".multRow input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.multRow").each(function () {
// check value entered for Percentage Grade
// & change Pass Level to value accordingly
var $num = 0;
if ($('.percGrade', this).val() > 85) {
$num = 1;
$('.passLevel',this).text($num);
}
// get the values from this row:
var $val1 = $('.credits', this).val();
var $val3 = $('.percGrade', this).val();
var $val2 = $('.passLevel', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
Since .passLevel is a text field, you should use .val instead of .text:
$('.passLevel',this).val($num);

Categories

Resources