Creating a simple calculator that manipulates innerHTML using javascript - javascript

I'm trying to make a simple weight and balance calculator for an airplane. The requirements are simple, I need to enter a weight and have a moment field updated to contain the weight multiplied by the known moment arm. Basically, I just need to multiply an input by a known value and have this product printed into another space.
Below is what I've tried so far, and it is supposed to work by:
Passing the value of the input dialogue using this.value on an onchange event
Find the output element uisng document.getElementById(outID)
Set the output element text using outID.innerHTML = weight*arm
However, nothing ever happens.
<!DOCTYPE html>
<head>
<script language="javascript" type="text/javascript">
function GetMoment(outID,weight,arm){
var outputObj = document.getElementById( outID );
outputObj.innerHTML = weight*arm;
}
</script>
</head>
<html>
<body>
<div id="InputForm" style="width:600;float:left;">
<table name="WeightAndBalance" border=4>
<tr>
<th>Front Seats</th>
<th> <input id="FrontWeight" type="text" name="FrontWeight" onchange="javascript:GetMoment(FrontMoment,this.value,85.5)"> </th>
<th>85.5 in</th>
<th> <span id="FrontMoment" type="text" name="FrontMoment" style="width:50px">Front Seat Moment</span></th>
</tr>
<tr>
<th>Rear Seats</th>
<th> <input id="RearWeight" type="text" name="RearWeight" onchange="javascript:GetMoment(RearMoment,this.value,117)"> </th>
<th>117 in</th>
<th> <span id="RearMoment" type="text" name="RearMoment">Rear Seat Moment</span></th>
</tr>
</table>
</div>
</body>
</html>

Change:
GetMoment(RearMoment,this.value,117)
to this form:
GetMoment('RearMoment',this.value,117)
each place that it occurs. An id is a string.
Also, javascript: is pretty old school - no need for it. It can just be like this:
<input id="RearWeight" type="text" name="RearWeight" onchange="GetMoment('RearMoment',this.value,117)">

Related

How to execute a function with different arguments while having multiple ID's in javascript?

I have a table showing me two parameters. What I would like to do is change the value of each of these parameters when a button is clicked. So each parameter has its own button with its own specific Ids (made with jinja2). for the value to be changed, I have to take the name of the parameter as an argument in a function, please look at the below picture:
my actual setup
So I have my input box and my button to be clicked:
<td> <input type=number size=5 id="{{key}}"> </td>
<td> <button onClick="change('{{key}}')" name="{{key}}">change value</button> </td>
the hard part is that, the change has to be made by executing a python script, so my function is described as :
function change(key){
$.getJSON($SCRIPT_ROOT + '/_change_value', {
a: $('input[name="key"]').val(),
b: $('button[name="key"]').val()}, function(data) { alert("Value was changed to " + data.result);});
}
For testing purpose I just made a python function that will return a only, to check if all went good, but unfortunately.
#app.route('/_change_value')
def change_value():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a)
a is returned as 0 always... I'm glad if someone can help me with this
I'm pretty sure the value key is not passed. Thanks a lot in advance
Edit: I made a mistake posting this question, id is present instead of name for the input, but still that did not resolve my problem...
Here you go with a solutio https://jsfiddle.net/1dvjqy11/
$('button').click(function(){
var a = $(this).closest('tr').find('input[type="number"]').val();
var b = $(this).closest('tr').find('td').first().html();
console.log(a, b);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>GPS_Inject_to</td>
<td>127</td>
<td>
<input type="number" size=5 />
</td>
<td>
<button>
Change Value
</button>
</td>
</tr>
<tr>
<td>RPM2_SCALING</td>
<td>1</td>
<td>
<input type="number" size=5 />
</td>
<td>
<button>
Change Value
</button>
</td>
</tr>
</tbody>
</table>
I've used jQuery closest to get the parent tr and used jQuery find method to find the child elements.
Hope this will help you.

Passing data from HTML to JS function

I have a series of data points that I query for status and voltage, and want to use a function to display as readable data in a table.
I can't seem to get how to pass the register data to the fnction, and then return the processed data to the table.
Here's the test code,
<input type="hidden" id="reg120" name="reg120" readonly value="%d">
<input type="hidden" id="reg121" name="reg121" readonly value="%d">
<script language="javascript">
function dsestate(regn) {
var state = ["STOP MODE","AUTO MODE","MANUAL MODE","TEST ON LOAD","AUTO MAN","USER CONF","TEST OFF LOAD","OFF"];
return state[regn];
}
</script>
<script language="javascript">
function divby10(regn1) {
return regn1/10;
}
</script>
<table id="maintable" style="width:75%">
<tr>
<th>Site</th>
<th style="width:180px">Status</th>
<th style="width:180px">Voltage</th>
</tr>
<tr>
<td><input type="text" id="dsestate(reg120)"></td>
<td><input type="text" id="divby10(reg121)"></td>
</tr>
</table>
</body>
</html>
Any help would be appreciated.
divBy10's argument should be a number (so it could be divided by 10).
dsestate's argument should also be a number so you can get the object by the index of the state Array (i.e. state[1]).
And since you're calling a javascript function, it should also use onload=, rather than id=.
I hope that gives you a starting point, good luck!

Real time calculation with PHP & array

For a client i'm currently working on their new system. In this system they can create bookings/invoices and send them to their clients.
On 1 page my client is needed to fill in the price for each container in the qoutation. My client asked me to make a new table column below the container columns with the total prices for all containers. I want to do this real time, so when my client fills in the prices the total price changes.
The only problem I stumble on is this:
I currently have PHP/MySQL function that collect all the containers from a certain quotation out of the database. With a while loop I create the needed html code for each of the containers. I made the input fields (where they fill in the prices) an array by naming the input fields like this:
<td>€ <input type="text" name="msg_container['.$i.'][ocean_freight]" value="'. $quote['ocean_freight'].'" style="width: 100px;" /></td>
The $i variable get's count up for each loop. It starts by 0 and ends when there are no containers left.
To make things a bit more detailed I have created a jsfiddle how the currently page looks like: https://jsfiddle.net/cwfmqbqv/
Now I'm not an expert in javascript so I'm stuck at this point. Long story short, how am I able to calculate all the values in the array in real time?
I've made a simple addition to your fiddle.
It's not complete as I only have time to make one for the Ocean Freight.
JSFiddle
$(document).ready(function() {
$(".oceanIn").keyup(function() {
var total = 0.0;
$.each($(".oceanIn"), function(key, input) {
if(input.value && !isNaN(input.value)) {
total += parseFloat(input.value);
}
});
$("#oceanTotal").html("Total: " + total);
});
});
Also I added some class and id to some of your elements to make it work.
Note
For this one, I used keyup but feel free to use different events like change or blur, or whatever fits your needs.
You should have tried to learn the basics of Javascript before you went and looked for a client.
Also, I think you're confused between a column and a row.
What you want is written in pure js in the following update to your jsfiddle:
JSFiddle
The principal concept here was using the change event on inputs. Furthermore, I didn't change the naming of your inputs but consider better conventions.
In the total function, we get a type of columns we're dealing with (using custom attributes is better than just using input names. eg: column-type="thc") and calculate the total number of each related input.
It uses Regular Expression (RegExp) in your case to find the right column out of input names. Mind that ~~ is just a simple hack for text to integer conversion in JavaScript.
Next we find all inputs and attach an event listener using addEventListener to each for the change event type. In this delegate, we find the appropriate input for total function and span IDs corresponding the column the input represents, again using RegExp but this time implicitly. Then change the corresponding span based on the total return value;
This is similar to the first answer, but more complete, and the addition fires on keyup instead of on blur. It applies to all the columns without needing to create separate functions for each. Here's the fiddle.
Javascript
$(function(){
$(".ocean-input, .bunker-input, .thc-input, .road-input").on("keyup", function()
{
var total = 0;
$("." + $(this).attr('class')).each(function()
{
total += parseFloat($(this).val().replace('', 0).replace(',', '.'));
});
$("#" + $(this).data("total-id")).html(total.toString().replace('.', ','));
});
});
HTML
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="font-family:Arial, sans-serif; color:#000; font-size:12px;">
<thead>
<tr>
<th width="50">Amount</th>
<th>Type</th>
<th>Weight (p/u)</th>
<th>Shipping owned</th>
<th>Ocean Freight</th>
<th>Bunker Surcharge</th>
<th>THC</th>
<th>Road transport</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Container Type 1</td>
<td>1000</td>
<td>No</td>
<td>€ <input type="text" class="ocean-input" data-total-id="ocean-total" name="msg_container[0][ocean_freight]" value="" style="width: 100px;"></td>
<td>€ <input type="text" class="bunker-input" data-total-id="bunker-total" name="msg_container[0][bunker_surcharge]" value="" style="width: 100px;"></td>
<td>€ <input type="text" class="thc-input" data-total-id="thc-total" name="msg_container[0][thc]" value="" style="width: 100px;"></td>
<td>€ <input type="text" class="road-input" data-total-id="road-total" name="msg_container[0][road_transport]" value="" style="width: 100px;"></td>
</tr><tr>
<td>1</td>
<td>Container Type 2</td>
<td>2500</td>
<td>No</td>
<td>€ <input type="text" class="ocean-input" data-total-id="ocean-total" name="msg_container[1][ocean_freight]" value="" style="width: 100px;"></td>
<td>€ <input type="text" class="bunker-input" data-total-id="bunker-total" name="msg_container[1][bunker_surcharge]" value="" style="width: 100px;"></td>
<td>€ <input type="text" class="thc-input" data-total-id="thc-total" name="msg_container[1][thc]" value="" style="width: 100px;"></td>
<td>€ <input type="text" class="road-input" data-total-id="road-total" name="msg_container[1][road_transport]" value="" style="width: 100px;"></td>
</tr> </tbody>
<tfoot>
<tr>
<th width="50"></th>
<th></th>
<th></th>
<th></th>
<th>Total: €<span id="ocean-total"></span></th>
<th>Total: €<span id="bunker-total"></span></th>
<th>Total: €<span id="thc-total"></span></th>
<th>Total: €<span id="road-total"></span></th>
</tr>
</tfoot>
</table>

Simply Javascript to total up form fields, where's my issue?

The goal is to take the number of orders for each type and calculate the total price for all of them when you click total cost. But I cant seem to get it to work google debugger says
Uncaught SyntaxError: Unexpected token ; 13
Uncaught ReferenceError: compute is not defined
Edit: Fixed the Parenthesis but now i'm having issues with the output lin that returns the total.
Edit2: added .value to return
[SOLVED]
<head>
<title>Coffee Order Form</title>
<script type="text/javascript">
function compute()
{
//input
var french = Number(document.getElementById("french").value;
if(isNaN(french))
{
french=0;
}
var hazelnut = Number(document.getElementById("hazelnut").value);
if(isNaN(hazelnut))
{
hazelnut=0;
}
var columbian = Number(document.getElementById("columbian").value);
if(isNaN(columbian))
{
columbian=0;
}
//calculate
var total = 3.49 * french + 3.95 * hazelnut + 4.59 * columbian;
//output
return document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
</head>
<body>
<form method="post" action="http://uta.edu">
<table border="2">
<caption><b>Coffee Order Form</b></caption>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<th>French Vanilla</th>
<th>$3.49</th>
<td><input type="text" id="french"></td>
</tr>
<tr>
<th>Hazelnut Cream</th>
<th>$3.95</th>
<td><input type="text" id="hazelnut"></td>
</tr>
<tr>
<th>Columbian</th>
<th>$4.59</th>
<td><input type="text" id="columbian"></td>
</tr>
</table>
<input type="button" value="Total Cost" onclick="compute()">
<input type="text" id="total">
<br/>
<input type="submit" value="Submit Order">
<input type="reset" value="Clear Order Form">
</form>
</body>
You are missing the ending parentheses for all 3 calls to Number():
var french = Number(document.getElementById("french").value;
Should be:
var french = Number(document.getElementById("french").value);
Because of the syntax error, the function is not available to your code within the Body. Thus, the uncaught reference error.
In multiple places parentheses are not balanced e.g.:
var french = Number(document.getElementById("french").value --->)<---- missing;
The best minimum practice is to put javascript code in .js files, use a tool like pychecker to check syntax of files and then you insert with
<script src=".."></script>
For even better results use jasmine or a similar framework to test your javascript code first.
All your Number functions lack the closing parenthesis:
var french = Number(document.getElementById("french").value);
var hazelnut = Number(document.getElementById("hazelnut").value);
var columbian = Number(document.getElementById("columbian").value);

How can I update a set of text fields on key press and avoid resetting a form on submit?

I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:
This is what I've tried:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output")
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" />
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).
Why is the form resetting, and how could I extend this to not need the button at all?
Here is the fiddle link for it:
Calculator
Use the below code to achieve what I think you want to :
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Please check this FIDDLE.
All you need to adding attributes data-formula to your table cells.
HTML
<table border="1">
<tr>
<td>
<input type="text" id="initial-val" />
</td>
<td>card board</td>
<td>recycled</td>
<td>reusable</td>
</tr>
<tr>
<td>lovely trees</td>
<td data-formula='val*5'></td>
<td data-formula='val+10'></td>
<td data-formula='val/2'></td>
</tr>
<tr>
<td>what is acres</td>
<td data-formula='val*2'></td>
<td data-formula='val*(1+1)'></td>
<td data-formula='val*(10/5)'></td>
</tr>
</table>
JAVASCRIPT
$(function () {
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var $input = $('#initial-val'),
$cells = $('td[data-formula]');
$input.on('keyup', function () {
var val = $input.val();
if (isNumber(val)) {
$.each($cells, function () {
var $thisCell = $(this);
$thisCell.text(
eval($thisCell.attr('data-formula').replace('val', val.toString()))
)
});
} else {
$cells.text('ERROR')
}
});
});
You'll need:
a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
an input field for user input
a submit button with a onclick() event which passes your input into your calculation
(you may want to do some validation on this so they can only enter numbers)
validation examples
your Javascript file that takes the input from your box on submit and performs your calculation
display the information back to user... something like innerHtml to an element you've selected or:
var output = document.getelementbyid("your outputbox")
output.value = "";
output.value = "your calculated value variable";
Here is a tutorial for grabbing user input.
Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:
HTML:
<table>
<tr>
<th></th>
<th>Recycled Cardboard</th>
<th>Re-usable Cardboard</th>
</tr>
<tr>
<th>Trees Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Acres Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Energy (in KW)</th>
<td></td><td></td>
</tr>
<tr>
<th>Water (in Gallons)</th>
<td></td><td></td>
</tr>
<tr>
<th>Landfill (Cubic Yards)</th>
<td></td><td></td>
</tr>
<tr>
<th>Air Pollution (in Lbs)</th>
<td></td><td></td>
</tr>
</table>
Javascript:
function showStats(cardboardTons) {
var elements = $("td");
var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
for(var i=0;i<coeffs.length;i++)
elemnts.eq(i).html(cardboardTons * coeffs);
}
Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.

Categories

Resources