Adding up inputs doesn't change javascript - javascript

I am trying to add up 3 input elements of type number. This doesn't work for some reason. When I take out the if statements, it works, but only after I change the first one (score1). When I change the others, nothing happens. Thanks.
function getTotal() {
var score1 = document.getElementById("score1");
var score2 = document.getElementById("score2");
var score3 = document.getElementById("score3");
var sc1 = parseInt(score1.value);
var sc2 = parseInt(score2.value);
var sc3 = parseInt(score3.value);
if (isNan(sc1)) {
sc1 = 0;
}
if (isNan(sc2)) {
sc2 = 0;
}
if (isNan(sc3)) {
sc3 = 0;
}
var total = sc1 + sc2 + sc3;
document.getElementById("totalScore").innerHTML = total;
}
function assign() {
var score1 = document.getElementbyId("score1");
var score2 = document.getElementbyId("score2");
var score3 = document.getElementbyId("score3");
score1.onchange = getTotal;
score2.onchange = getTotal;
score3.onchange = getTotal;
}
<!DOCTYPE html>
<html>
<head>
<script src="getTotal.js" type="text/javascript"></script>
</head>
<body>
<header>
<tbody>
<tr>
<td>
Total:
<output id="total" class="totalScore"></output>
</td>
</tr>
</tbody>
</header>
<table>
<tbody>
<td>Score 1</td>
<td><input type="number" id="score1"/></td>
<td>Score 2</td>
<td><input type="number" id="score2" /></td>
<td>Score 3</td>
<td><input type="number" id="score3" /></td>
</tbody>
</table>
<script type="text/javascript">assign();</script>
</body>
</html>

Spelling mistake.
var score1 = document.getElementbyId("score1");
var score2 = document.getElementbyId("score2");
var score3 = document.getElementbyId("score3");
If you check your console you will see the error Uncaught TypeError: undefined is not a function on the line where you are calling score1. The selector is document.getElement*By*Id, you were writing by lowercase..

Your <output> has an id attribute with the value is "total" whereas your class attribute' value is "totalscore". Consider changing the id value to "totalscore" or change getElementById's value to"score"

Related

Markup error: document.getElementById(...) is null or not an object

I am working on a Script for sorting boxes.
Here my problem.
In the code:
Size_XS = document.getElementById('Size_XS'+i).value*1;
seems to work without any problem.
While this one:
document.getElementById('Size_XS'+i).value = Size_XS;
will give me the error message: document.getElementById(...) is null or not an object.
if I change to:
document.getElementById('Size_XS1').value = Size_XS;
It all works, but then I cannot loop the file later and why does it work with i above?
My script below:
function calcbox(){
var count = document.getElementById('count').value*1;
count = count+1;
var box_num = 0;
var header = "<table style='border:#000 1px solid; background-color:#fff;'><tr><td width='25'><b>Box</b></td><td width='200'><b>Item name</b></td><td width='100'><b>Sizes</b></td><td width='250'><b>Pcs</b></td></tr>";
var output = header+document.getElementById('output').innerHTML;
var total_qty;
var box_qty;
var item_name;
var Size_XS=0;
var Size_S=0;
var Size_M=0;
var Size_L=0;
/*for(var i=1;i<count;i++){*/
var i=1;
total_qty = document.getElementById('total_qty'+i).value*1;
box_qty = document.getElementById('box_qty'+i).value*1;
item_name = document.getElementById('item_name'+i).value;
Size_XS = document.getElementById('Size_XS'+i).value*1;
Size_S = document.getElementById('Size_S'+i).value*1;
Size_M = document.getElementById('Size_M'+i).value*1;
Size_L = document.getElementById('Size_L'+i).value*1;
//Packing whole boxes
if(Size_XS>=box_qty){
var Box_count = parseInt(Size_XS/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+"</td><td>S</td><td>"+box_qty+"</td></tr>";
}
Size_XS = Size_XS-(box_qty*Box_count);
alert(Size_XS);
document.getElementById('Size_XS'+i).value = Size_XS;
}
if(Size_S>=box_qty){
var Box_count = parseInt(Size_S/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+"</td><td>S</td><td>"+box_qty+"</td></tr>";
}
Size_S = Size_S-(box_qty*Box_count);
document.getElementById('Size_S'+i).value = Size_S;
}
if(Size_M>=box_qty){
var Box_count = parseInt(Size_M/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+"</td><td>M</td><td>"+box_qty+"</td></tr>";
}
Size_M = Size_M-(box_qty*Box_count);
document.getElementById('Size_M'+i).value = Size_M;
}
if(Size_L>=box_qty){
var Box_count = parseInt(Size_L/box_qty);
for(var i=1;i<=Box_count;i++){
box_num = box_num+1;
output = output+"<tr><td>"+box_num+"</td><td>"+item_name+" </td><td>L</td><td>"+box_qty+"</td></tr>";
}
Size_L = Size_L-(box_qty*Box_count);
document.getElementById('Size_L'+i).value = Size_L;
}
document.getElementById("output").innerHTML = output+"</table>";
document.getElementById("qty_boxes").value = box_num;
show('Volume_weight');
}
I'm getting my values from here in the HTML code:
<table>
<tr>
<td width="10">1</td>
<td width="120"><input id="item_name1" type="text" style="width:100px;" /></td>
<td width="80"><input id="box_qty1" type="text" style="width:30px;" /></td>
<td width="40"><input id="Size_XS1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="40"><input id="Size_S1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="40"><input id="Size_M1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="40"><input id="Size_L1" type="text" style="width:30px;" onchange="totcalc(1);" /></td>
<td width="60"><input id="total_qty1" type="text" style="width:50px;" /></td>
</tr>
</table>
You have used i for two different things in the code. Firstly as a suffix to input element id values, and secondly as a loop counter for boxes. After i is no longer equal to 1 after various loops complete, the HTML element lookup by suffixed id fails:
document.getElementById('Size_XS'+i).value = Size_XS;
occurs after
for(var i=1;i<=Box_count;i++){ // ...
Feel free to delete the question if this is the problem :D

Javascript Range, Variance, and Standard Deviation Functions

So, I've been recently tasked to do a few calculations and to build a custom JS statistics library. The only 3 things I have left are to create functions for the range, variance, and standard deviation. What I'm doing here is passing my array (x) into the js functions, but they keep coming up blank. Am I doing something wrong?
function findSum(x)
{
var sum = 0;
for(i = 0; i < x.length; i++)
{
sum = sum + x[i];
}
return sum;
};
function findMean(x)
{
return findSum(x) / x.length;
};
function findMedian(x)
{
x.sort( function(a,b) {return a - b;} );
var half = Math.floor(x.length/2);
if(x.length % 2)
return x[half];
else
return (x[half-1] + x[half]) / 2.0;
}
// Ascending functions for sort
function ascNum(a, b) { return a - b; }
function clip(arg, min, max) {
return Math.max(min, Math.min(arg, max));
};
function findMode(x)
{
var arrLen = x.length;
var _arr = x.slice().sort(ascNum);
var count = 1;
var maxCount = 0;
var numMaxCount = 0;
var mode_arr = [];
var i;
for (i = 0; i < arrLen; i++) {
if (_arr[i] === _arr[i + 1]) {
count++;
} else {
if (count > maxCount) {
mode_arr = [_arr[i]];
maxCount = count;
numMaxCount = 0;
}
// are there multiple max counts
else if (count === maxCount) {
mode_arr.push(_arr[i]);
numMaxCount++;
}
// resetting count for new value in array
count = 1;
}
}
return numMaxCount === 0 ? mode_arr[0] : mode_arr;
};
function findRange(x)
{
x.sort( function (a, b) {return a-b;} );
}
function findVariance(x) {
var mean = findMean(x);
return findMean(array.map(findSum(sum)) {
return Math.pow(sum - mean, 2);
}));
},
function findStandardDeviation(x)
{
return Math.sqrt(findVariance(x));
};
The HTML code:
<html>
<head>
<h1>Statistical Calculations</h1>
<title>Calculating Stats</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='Stats.js'></script>
<script language="JavaScript">
function addNumber()
{
var input = document.getElementById('input').value;
var list = document.getElementById('list');
var option = document.createElement('OPTION');
list.options.add(option);
option.text = input;
}
function getStatistics()
{
var list = new Array();
var select = document.getElementById('list');
for(i = 0; i < select.options.length; i++)
{
list[i] = parseInt(select.options[i].text);
}
document.getElementById('summation').value =findSum(list);
document.getElementById('mean').value = findMean(list);
document.getElementById('median').value = findMedian(list);
document.getElementById('mode').value = findMode(list);
document.getElementById('variance').value = findVariance(list);
document.getElementById('standardDev').value = findStandardDeviation(list);
document.getElementById('range').value = findRange(list);
document.getElementById('max').value = findMax(list);
document.getElementById('min').value = findMin(list);
}
</script>
</head>
<body>
<table>
<tr>
<td>Input Number:</td><td><input type='text' id='input'></td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Add Number' onClick='addNumber()'></td>
</tr>
<tr>
<td colspan='2'>
<select id='list' size='5'>
</select>
</td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Calculate!' onClick='getStatistics()'></td>
</tr>
<tr>
<td>Summation:</td><td><input type='text' id='summation' readonly></td>
</tr>
<tr>
<td>Mean:</td><td><input type='text' id='mean' readonly></td>
</tr>
<tr>
<td>Median:</td><td><input type='text' id='median' readonly> </td>
</tr>
<tr>
<td>Mode:</td><td><input type='text' id='mode' readonly></td>
</tr>
<tr>
<td>Max:</td><td><input type='text' id='max' readonly></td>
</tr>
<tr>
<td>Min:</td><td><input type='text' id='min' readonly></td>
</tr>
<tr>
<td>Range:</td><td><input type='text' id='range' readonly></td>
</tr>
<tr>
<td>Variance:</td><td><input type='text' id='variance' readonly></td>
</tr>
<tr>
<td>Standard Deviation:</td><td><input type='text' id='standardDev' readonly></td>
</tr>
</table>
</body>
</html>
The last 3 seem to do absolutely nothing, and I've been bashing my head in for the last few days trying to figure it out. If anyone could help sort my functions out into working order, it'd be greatly appreciated! I'm sure that the array has been passing into the functions correctly, seeing as the first 4 functions obviously worked.

How to count value in rows cell table

If I have more than 1 rows where each rows have 3 column with the inputbox , maybe look like this:
<table id="mytable">
<tr>
<td><input value = "1" /></td>
<td><input value = "2" onBlur="goCount(this)" /></td>
<td><input value = "2+1" /></td>
</tr>
<tr>
<td><input value = "3" /></td>
<td><input value = "4" onBlur="goCount(this)" /></td>
<td><input value = "3+4" /></td>
</tr>
counting must be between cell 1 + cell 2 and the result will show in third cell, maybe the function must be like this :
function goCount(btn) {
var x = btn.value;
var y = ??? ;
var z = x + y;
}
but I do not know how to do that, First get the cell 1 as value and put the result on cell 3 but still in each same rows
is there someone who would help me to resolve this, thanks ^^
Here is your solution
Demo
Your code should be like this
<table id="mytable">
<tr>
<td><input value = "1" onBlur="goCount(this)"/></td>
<td><input value = "2" onBlur="goCount(this)" /></td>
<td><input value = "" id="result"/></td>
</tr>
<tr>
<td><input value = "3" /></td>
<td><input value = "4" onBlur="goCount(this)" /></td>
<td><input value = "" /></td>
</tr>
<script type="text/javascript">
function goCount(btn) {
var x = btn.value;
//var y = ??? ;
var res= document.getElementById("result") ;
//alert( res.value);
if(res.value == "") {
res.value = 0 ;
}
res.value = parseInt(res.value) + parseInt(x) ;
}
</script>
Note: Here is one thing you should note, I have used particular ID to return value in that, if you are using this for many rows you should use jQuery to navigate to that element in respective row and print result in it.

dynamic pricing table list

i am writing a code to select/remove the product from display table, and when the product is selected,then product with its price mus be displayed in some other table where at the end sum total is also needed which get updated as per selected product prices
<table id="table-example" class="table">
<thead>
<tr>
<th>Cause</th>
<th>Monthly Charge</th>
</tr>
</thead>
<tbody>
<tr>
<div id="selectedServices"></div>
<td id="myDiv"></td>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<table id="table-example" class="table">
<thead>
<tr>
<th>Cause</th>
<th>Monthly Charge</th>
</tr>
</thead>
<div>
<tbody>
<p>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>table</label>
</td>
<td>80</td>
</tr>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>chair</label>
</td>
<td>45</td>
</tr>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>set</label>
</td>
<td>10</td>
</tr>
</tbody>
</div>
</table>
script
$(function() {
$(":checkbox").change(function() {
var arr = $(":checkbox:checked").map(function() { return $(this).next().text(); }).get();
$("#myDiv").text(arr.join(','));
});
});
function ToggleBGColour(item) {
var td = $(item).parent();
if (td.is('.rowSelected'))
td.removeClass("rowSelected");
else
td.addClass("rowSelected");
}
Here is the corresponding fiddle.
Based on your comment for my other answer, this should work for you then:
$(":checkbox").change(function () {
// Toggle class of selected row
$(this).parent().toggleClass("rowSelected");
// Get all items name, sum total amount
var sum = 0;
var arr = $(":checkbox:checked").map(function () {
sum += Number($(this).parents('tr').find('td:last').text());
return $(this).parents('tr').clone();
}).get();
// Display selected items and their sum
$("#selectedServices").html(arr).find('input').remove();
$("#total").text(sum);
});
This avoids the need for creating new HTML elements in the JavaScript code, and reduces the number of .maps() and .each() loops to one.
http://jsfiddle.net/samliew/uF2Ba/
Here is the javascript for but u need to remove onClick attrs :
$(function() {
$(":checkbox").change(function() {
ToggleBGColour(this);
var arr = $(":checkbox:checked").map(function() {
return $(this).next().text();
}).get();
var nums = $(":checkbox:checked").map(function() {
return parseInt($(this).parent().next().html());
}).get();
var total = 0;
for (var i = 0; i < nums.length; i++) {
total += nums[i] << 0;
}
$("#myDiv").text(arr.join(',') + 'total : '+total);
});
});
function ToggleBGColour(item) {
var td = $(item).parent();
if (td.is('.rowSelected'))
td.removeClass("rowSelected");
else
td.addClass("rowSelected");
}
I updated your fiddle with my answer : http://jsfiddle.net/A2SKr/9/
Here's what i've changed.
Slightly better formatted.
i removed the onclick attribute. Its bad practice to use this because of performance issues. Use delegates
Ive also changed a lil bit of your HTML. the output is now a table
added a total element to the output as well
javascript code :
$(":checkbox").change(function () {
var total = 0;
var check = $(":checkbox:checked");
var causes = check.map(function () {
return $(this).next().text();
}).get();
var costs = check.map(function () {
return $(this).parent().next().text()
}).get();
var tbody = $("#table-example tbody").empty();
$.each(causes, function (i, cause) {
tbody.append("<tr><td>" + cause + "</td><td id='" + i + "'><td/></tr>");
});
$.each(costs, function (i, cost) {
$('#' + i + '').html(cost);
total += parseInt(cost, 10);
});
tbody.append("<tr><td>Total</td><td>" + total + "<td/></tr>");
});
});

Javascript: Get number values from dynamic Javascript table and Input box then do calculation

This is for a project in progress. I need to create a calculation that will grab the number from the 'total' row in the 'off column' in the table, then minus this from the starting balance that is defined in the input box. The result of this calculation then needs to be displayed in an alert box when the submit button is clicked.
It's a bit beyond me and if anyone could point me in the right direction I would be grateful.
HTML:
<!DOCTYPE html>
<html>
<head>
<h1><em>EXPENSES CALCULATOR</em></h1>
<link rel="stylesheet" type="text/css" href="tt.css"/>
</head>
<body>
<p id="balance">Starting balance (£)<input type="number"></p>
<p>
<input type="button" id="addNewRow" value="Add new row">
<input type="button" onClick="window.print()" value="Print your purchases"/>
</p>
<table id="breakdowntable">
<tr>
<th>Payment type</th>
<th>Off</th>
<th>To come off</th>
<th>Total</th>
</tr>
<tr id="card">
<th>Card Payment</th>
<td>0</td>
<td>0</td>
<td id="cardtotal">0</td>
</tr>
<tr id="cash">
<th>Cash Payment</th>
<td>0</td>
<td>0</td>
<td id="cashtotal">0</td>
</tr>
<tr id="other">
<th>Other Payment</th>
<td>0</td>
<td>0</td>
<td id="othertotal">0</td>
</tr>
<tr id="total">
<th>Total</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<table id="purchases"> </table>
<p><input type="Submit" id="submit" onclick='alert(money_to_number())'> </p>
<script type="text/javascript" src="tt.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"> </script>
</body>
</html>
JavaScript:
var doc = document;
function calculateAmount() {
var purchases = doc.getElementById('purchases');
var purchasesRows = purchases.rows;
var typeValue = {'CP' : [0,0], 'CA' : [0,0], 'OP' : [0,0]};
for (var i = 0, purchasesRowsLength = purchasesRows.length, pytType, inputs, isItOffInput, isItOff; i < purchasesRowsLength; ++i) {
pytType = purchasesRows[i].getElementsByTagName('SELECT')[0];
inputs = purchasesRows[i].getElementsByTagName('INPUT');
isItOffInput = inputs[0];
isItOff = inputs[inputs.length - 1].checked ? 0 : 1;
typeValue[pytType.value][isItOff] += isItOffInput.value - 0;
}
var total = [0, 0];
var cardCells = doc.getElementById('card').cells;
cardCells[1].innerHTML = typeValue['CP'][0];
total[0] += typeValue['CP'][0];
cardCells[2].innerHTML = typeValue['CP'][1];
total[1] += typeValue['CP'][1];
cardCells[3].innerHTML = typeValue['CP'][0] + typeValue['CP'][1];
var cashCells = doc.getElementById('cash').cells;
cashCells[1].innerHTML = typeValue['CA'][0];
total[0] += typeValue['CA'][0];
cashCells[2].innerHTML = typeValue['CA'][1];
total[1] += typeValue['CA'][1];
cashCells[3].innerHTML = typeValue['CA'][0] + typeValue['CA'][1];
var otherCells = doc.getElementById('other').cells;
otherCells[1].innerHTML = typeValue['OP'][0];
total[0] += typeValue['OP'][0];
otherCells[2].innerHTML = typeValue['OP'][1];
total[1] += typeValue['OP'][1];
otherCells[3].innerHTML = typeValue['OP'][0] + typeValue['OP'][1];
var totalCells = doc.getElementById('total').cells;
totalCells[1].innerHTML = total[0];
totalCells[2].innerHTML = total[1];
totalCells[3].innerHTML = total[0] + total[1];
}
function addNewRow() {
var purchases = doc.getElementById('purchases');
var row = purchases.insertRow(purchases.rows.length);
var pytTypeCell = row.insertCell(0);
var type = [['CP', 'Paid by Card £'], ['CA', 'Paid with Cash £'], ['OP', 'Other Payment type £']];
var pytType = doc.createElement('SELECT');
for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) {
option = doc.createElement('OPTION');
option.value = type[i][0];
option.innerHTML = type[i][1];
pytType.appendChild(option);
}
pytType.onchange = calculateAmount;
var pytTypeLabel = doc.createElement('LABEL');
pytTypeLabel.innerHTML = 'Type';
pytTypeLabel.appendChild(pytType);
pytTypeCell.appendChild(pytTypeLabel);
var isItOffInput = doc.createElement('INPUT');
isItOffInput.type = 'number';
isItOffInput.onkeyup = calculateAmount;
pytTypeCell.appendChild(isItOffInput);
var descriptInputCell = row.insertCell(1);
var descriptInput = doc.createElement('INPUT');
descriptInput.type = 'number';
var descriptLabel = doc.createElement('LABEL');
descriptLabel.innerHTML = 'Description';
descriptLabel.appendChild(descriptInput);
descriptInputCell.appendChild(descriptLabel);
var dateInputCell = row.insertCell(2);
var dateInput = doc.createElement('INPUT');
dateInput.type = 'date';
var dateLabel = doc.createElement('LABEL');
dateLabel.innerHTML = 'Payment Date';
dateLabel.appendChild(dateInput);
dateInputCell.appendChild(dateLabel);
var isItOffCheckBoxCell = row.insertCell(3);
var isItOffCheckBox = doc.createElement('INPUT');
isItOffCheckBox.type = 'checkbox';
isItOffCheckBox.onclick = calculateAmount;
var isItOffLabel = doc.createElement('LABEL');
isItOffLabel.appendChild(isItOffCheckBox);
isItOffLabel.appendChild(document.createTextNode('Is it Off?'));
isItOffCheckBoxCell.appendChild(isItOffLabel);
}
doc.getElementById('addNewRow').onclick = addNewRow;
window.onload = function() {
addNewRow();
};
Here it is in a jsFiddle: http://jsfiddle.net/jfBAJ/
You need to give ids to the elements you want to find later. I gave your starting balance input the id "starting_balance" and I gave your grand total TD the id of "grand_total" then wrote the following onSubmit:
document.getElementById("submit").onclick = onSubmit
function onSubmit(){
var starting = document.getElementById("starting_balance").value;
var grandTotal = document.getElementById("grand_total").innerHTML;
var finalBalance =parseFloat(grandTotal||0) + parseFloat(starting||0);
alert(finalBalance);
}
This alerts the new total + the starting balance.

Categories