JavaScript calculator functionality - javascript

I am working on a project where calculator functionality is needed and there should be support for adding more values through JavaScript and also print out the sum from all the numbers in the document.
The digits entered need to be two-digit numbers. Blank or non-numeric data should be skipped.
Here is what I have so far:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sum Calculator</title>
</head>
<body>
Number of Rows: <input type= text value=2 style="width:30px" maxlength=2 > <input type=button value='Change' onclick="" />
<br /><br />
<table cellspacing=0 cellpadding=4>
<tr><td>Number 1:</td><td><input value=20 style="width:30px" type=text maxlength=2/></td></tr>
<tr><td>Number 2:</td><td><input value=25 style="width:30px" type=text maxlength=2/></td></tr>
<tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
</table>
<input type=button value='Recalculate Sum' onclick="" />
</body>
</html>
Any advice how I can add another row in the table with JavaScript and calculate the end result of all the fields in the table?

Quite easy actually. Do this:
<table cellspacing=0 cellpadding=4>
<tbody id="whateverId">
<tr><td>Number 1:</td><td><input value=20 style="width:30px" type=text maxlength=2/></td></tr>
<tr><td>Number 2:</td><td><input value=25 style="width:30px" type=text maxlength=2/></td></tr>
<tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
</tbody>
</table>
The js for creating:
var trEl = document.createElement('tr');
trEl.setAttribute('attribute', 'value'); // replace that with what you need
var tdEl = document.createElement('td');
// Here set td attributes
trEl.appendChild(tdEl);
// And same for the input im to lasy to write.
document.getElementById('whateverId').appendChild(trEl);
And... that's it. Group it in a function or whatever you want.
For the sum you just do something like:
var s = 0;
for (var i = 0; i < document.getElementById('whateverId').childNodes.length; i++)
{
s += document.getElementById(whateverId).childNodes[i].firstChild.firstChild.value; // Hope I counted the first childs right.... you get the point.
}

Related

How to fix sum of multiple input fields if same class in one <td contenteditable> not <td><input>

I can't sum on table td "jumlah" for "total"
<script>
$(document).on("change", ".jumlah", function() {
var sum = 0;
$(".jumlah").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
</script>
<input type="text" id="total" class="total" value="" />
I expect the output for total from jumlah
Elements with the [contenteditable] attribute will not have a [value] attribute because:
Only non-interactive, non-void, flow and phrase elements like <div></div>, <section></section>, <spab></span> etc. can have [contenteditable].
Only form controls such as <input>, <textarea>, <output>, etc. can have the [value] attribute.
So instead of .val() use .text() since text is the content between the tags of non-form controls. The important change is a ternary:
if this is an input get its value otherwise get its text
sum += $(this).is('input') ? +$(this).val() : +$(this).text();
The minor changes are:
input event instead of change because it looks slick.
The form is registered to the input event instead of document.
$('.totals').on("input", ".subtotal", function() {
let sum = 0;
$(".subtotal").each(function(){
sum += $(this).is('input') ? +$(this).val() : +$(this).text();
});
$(".total").val(sum);
});
:root {font:700 16px/1.2 Consolas}
input, output, data {display:inline-block;font:inherit;text-align:right;width:125px;}
output, data {width:50px}
data {outline:1px solid #aaa;padding:2px 17px 2px 0px;margin:1px 0px 1px 2px;width:110px}
<form class='totals'>
<table>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td>Total: <output class="total">0</output></td></tr>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have created a very simple example with what you need, I think you can easily implement something similar in your code.
$('.jumlah').on('input', function() {
let elementsToSum = $(document).find('.jumlah');
let sum = 0;
for (let ele of elementsToSum) {
// Parse the value of the <td> to integer
let eleIntValue = parseInt($(ele).html());
if (!isNaN(eleIntValue)) {
// Only add it to the sum if it is a number (not empty)
sum += eleIntValue;
}
}
// Change the value of <input> with the new calculated sum
$('#total').val(sum);
});
td {
width: 50px;
}
<table border="1">
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
</table>
<br>
<input type="text" id="total" class="total" value="" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Is there a way to add the total of a div?

I am having trouble trying to add the total of a div from an array. I am trying to add the total miles for the input and put it in a table. I want to just add the miles together, not the flight numbers. I would also like to have an id set for it so that I can call on to the total miles in another section.
var FlightNumber = new Array();
var Miles = new Array();
function insert() {
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length] = FlightNumberValue;
Miles[Miles.length] = MilesValue;
}
function showFlightNumber() {
var content = "<b></b><br>";
for (var i = 0; i < FlightNumber.length; i++) {
content += FlightNumber[i] + "<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content = "<b></b><br>";
for (var i = 0; i < Miles.length; i++) {
content += Miles[i] + "<br>";
}
document.getElementById('display2').innerHTML = content;
}
table,
th,
td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles.
<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();"> <br>
<input type="button" value="Show miles" onclick="showMiles();"> <br>
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td>
<div id="display">
</div>
</td>
<td>
<div id="display2">
</div>
</td>
</tr>
<td>Total Miles:</td>
<td></td>
</table>
I was able to get the miles to total by putting an id on the total column. Then I was able to use the Miles array you created and just parse the string value to an int and total those values.
Please note this code is not very clean. When you insert a new flight you should really be inserting a new row, not break lines. There are javascript frameworks out there that make it really easy to iterate over arrays, e.g. AngularJs / Angular / React / Vue.js.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();"> <br>
<input type="button" value="Show miles" onclick="showMiles();"> <br>
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
</body>
</html>

print javascript results into div tag

I have been able to make this work as it adds into <div></div> tags now I want to remove this array numbers 0,1,2,3 and feed the data into <div></div> tags in HTML, How can this be done, How do I make it insert inside the div tags
<html>
<head></head>
<title>Js test</title>
<h1>Js Test</h2>
<body>
<script type="text/javascript">
var data = new Array();
function addElement(){
data.push(document.getElementById('ins_name').value);
data.push(document.getElementById('gpa').value);
data.push(document.getElementById('da').value);
document.getElementById('ins_name').value='';
document.getElementById('gpa').value='';
document.getElementById('da').value='';
display();
}
function display(){
var str = '';
for (i=0; i<data.length;i++)
{
//str+="<tr><td>" + data[i] + "</td></tr>";
"<tr>
<td align=center width=176>Institution </td>
<td align=center>GPA</td>
<td align=center width=187>Degree Awarded</td>
</tr>"
"<tr>
<td align=center width=176> </td>
<td align=center> </td>
<td align=center width=187> </td>
</tr>"
}
document.getElementById('display').innerHTML = str;
}
</script>
<form name="jamestown" id="jamestown" method="post" action="samris.php" />
Institution : <input type="text" name="ins_name" id="ins_name" /></br>
GPA : <input type="text" name="gpa" id="gpa" /></br>
Degree Awarded : <input type="text" name="da" id="da" /></br>
</p>
<input type="button" name="btn_test" id="btn_test" value="Button Add Test" onClick='addElement()'; /></br>
</form>
<div id=display></div>
</body>
</html>
Since you've been adding more and more requirements in the comments, the innerHTML += "" approach stops working.
I advice you to create elements using document.createElement and add them to your document using Node.appendChild.
It's not really an answer to the initial question, but I figured it helps you more than continuing conversation in the comments. Maybe you can edit your question to reflect the additional requirements.
Let me know if there's stuff I used that you don't yet understand. Happy to elaborate!
var inputIds = ["ins_name", "gpa", "da"];
var inputElements = inputIds.map(getById);
var tbody = getById("display");
// Create a new row with cells, clear the inputs and add to tbody
function addRow() {
// Create a row element <tr></tr>
var row = document.createElement("tr");
inputElements.forEach(function(input) {
// For each input, create a cell
var td = document.createElement("td");
// Add the value of the input to the cell
td.textContent = input.value;
// Add the cell to the row
row.appendChild(td);
// Clear the input value
input.value = "";
});
// Add the new row to the table body
tbody.appendChild(row);
}
getById("btn_test").addEventListener("click", addRow);
// I added this function because document.getElementById is a bit too long to type and doesnt work with `map` without binding to document
function getById(id) {
return document.getElementById(id);
}
Institution : <input type="text" name="ins_name" id="ins_name" /><br>
GPA : <input type="text" name="gpa" id="gpa" /><br>
Degree Awarded : <input type="text" name="da" id="da" /><br>
<input type="button" id="btn_test" name="btn_test" value="Add Test"/><br>
<table>
<thead>
<tr>
<th>Institution</th>
<th>GPA</th>
<th>Degree</th>
</tr>
</thead>
<tbody id="display">
</tbody>
</table>

JavaScript and HTML Formatting - Table Needs to Call Variable

I'm a high-school student trying to make a proof writing program. I just need the JS function Edit() to send the value of the first text-box to the table. Any ideas? I know the code is messy, I'll fix it later.
Code:
<HTML>
<body>
<font size="5">
<p align="center">
<p1>Insert Given:</p1>
<div align="center"; id="Input1">
<form id='user-input'>
<input type='text' id='given' placeholder='Given Information'></input>
</form>
<p2>Insert Statement<br>to Prove:</p2>
<br>
<div align="center"; id="Input2">
<form id='user-input'>
<input type='text' id='prove' placeholder='Statement to Prove'></input>
</form>
<button id='Submit' Value='Edit' onClick="edit()">Submit</button>
<script>
function edit()
{
var x = document.getElementById('given').value;
var y = document.getElementById('prove').value;
document.getElementById('Test').innerHTML.value=var x
}
</script>
<br>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<table style="width:100%">
<col Width="15">
<col Width="300">
<col Width="500">
<tr>
<th>Step Number</th>
<th>Step</th>
<th>Explaination</th>
</tr>
<tr>
<td>1</td>
<td id='Test'></td>
<td>Given</td>
</table>
</div>
</body>
</html>
You can use textContent and not var keyword to read the x value. → document.getElementById('Test').textContent=x;
<HTML>
<body>
<font size="5">
<p align="center">
<p1>Insert Given:</p1>
<div align="center"; id="Input1">
<form id='user-input'>
<input type='text' id='given' placeholder='Given Information'></input>
</form>
<p2>Insert Statement<br>to Prove:</p2>
<br>
<div align="center"; id="Input2">
<form id='user-input'>
<input type='text' id='prove' placeholder='Statement to Prove'></input>
</form>
<button id='Submit' Value='Edit' onClick="edit()">Submit</button>
<script>
function edit()
{
var x = document.getElementById('given').value;
var y = document.getElementById('prove').value;
document.getElementById('Test').textContent=x;
}
</script>
<br>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<table style="width:100%">
<col Width="15">
<col Width="300">
<col Width="500">
<tr>
<th>Step Number</th>
<th>Step</th>
<th>Explaination</th>
</tr>
<tr>
<td>1</td>
<td id='Test'></td>
<td>Given</td>
</table>
</div>
</body>
</html>
! just add onChange="edit()" to first input and a little change in test function.
<input type='text' id='given' placeholder='Given Information' onChange="edit()"></input>
and
function edit(){
var x = document.getElementById('given').value;
var y = document.getElementById('prove').value;
document.getElementById('Test').innerHTML = x;}
var x is used to declare variables. And you don't need to edit innerHTML.value (I think this doesn't even exist). You just have to edit innerHTML
So, replace
document.getElementById('Test').innerHTML.value=var x
with
document.getElementById('Test').innerHTML = x
I'm not sure what you try to do but this will works better:
document.getElementById('Test').innerHTML = x;
So, if you want only to modify DOM and insert values I would suggest you to use:
insertRow() and insertCell() methods
This suggestion is based on this w3schools example,
and here is a specific jsfiddle for your case.
Definition and Usage
The insertRow() method creates an empty element and adds it to a table.
The insertRow() method inserts the new row(s) at the specified index in the table.
Note: A element must contain one or more or elements.
Tip: Use the deleteRow() method to remove a row.
For example a simple test would be:
function edit() {
var table = document.getElementById("myTable");
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = document.getElementById("given").value;
cell2.innerHTML = document.getElementById("prove").value;
cell3.innerHTML = cell1.innerHTML + cell2.innerHTML
}
Hope this helps!

Adding Row using Javascript Error

I was trying to create a program to add rows dynamically using Javascript in HTML Table using the Add Row Button. There seems to be an error.
<html>
<head>
<title>Home - First Website</title>
<style>
table{
width: 100%;
}
td{
padding: 8px;
border: 1px solid;
}
input[type="text"]{
width: 100%;
}
</style>
<script type="text/javascript">
function add(){
var num=parseInt(document.getElementById("t1").length+1);
var a=document.createElement("td");
var anode=document.createTextNode(num);
a.appendChild(anode);
document.getElementById("t1").appendChild(a);
a=document.createElement("td");
anode=document.createElement("input");
var b=document.createAttribute("type");
b.value="checkbox";
anode.setAttributeNode(b);
a.appendChild(anode);
document.getElementById("t1").appendChild(a);
a=document.createElement("td");
anode=document.createElement("input");
b=document.createAttribute("type");
b.value="text";
anode.setAttributeNode(b);
a.appendChild(anode);
document.getElementById("t1").appendChild(a);
}
</script>
</head>
<body>
<table name="t1">
<tr>
<input type="button" value="Add Row" onclick="add()">
</tr>
<tr>
<td>1.</td><td><input type="checkbox"></td><td><input type="text" style="width:100%;"></td>
</tr>
</table>
</body>
</html>
There are multiple problems in the code :
1) for adding row why are you doing this :
var num=parseInt(document.getElementById("t1").length+1);
: please note you haven't given your table any id.
I think you need count to number your rows. You can get that by :
var num =document.getElementById("t1").rows.length;
2) For adding a row, you have not created <tr> element!
Here's the corrected jsFiddle :
http://jsfiddle.net/thecbuilder/kCm2D/1/
update : changed the way to get number of rows.
js
function add() {
var num = var num =document.getElementById("t1").rows.length;
console.log(num);
var x = document.createElement("tr");
var a = document.createElement("td");
var anode = document.createTextNode(num);
a.appendChild(anode);
x.appendChild(a);
a = document.createElement("td");
anode = document.createElement("input");
var b = document.createAttribute("type");
b.value = "checkbox";
anode.setAttributeNode(b);
a.appendChild(anode);
x.appendChild(a);
a = document.createElement("td");
anode = document.createElement("input");
b = document.createAttribute("type");
b.value = "text";
anode.setAttributeNode(b);
a.appendChild(anode);
x.appendChild(a);
document.getElementById("t1").appendChild(x);
}
html
<table id="t1" name="t1"> <!-- "t1" is id as well -->
<tr>
<input type="button" value="Add Row" onclick="add()" />
</tr>
<tr>
<td>1.</td>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" style="width:100%;" />
</td>
</tr>
</table>
You're using getElementById but your table has a name not an id.
<table name="t1">
to
<table id="t1">
The error is on document.getElementById("t1"), but your table doesn't have an id="t1", it has a name="ti".
Update to this:
<table id="t1">

Categories