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

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);

Related

2sxc - Calculated vars between razor and JS on a #foreach loop

I'm creating a view with two text inputs ('est' being calculated via JS based on 'idd') on top, and then a table with a #foreach loop to display all my data. Some fields will be calculated based on each other, but others must be calculated after the page is loaded, every time the 'est' and/or 'idd' inputs change.
Since razor is calculated server side and this JS client side, how can I set these type of calculated columns like the one in this example:
This should be the myResult var (or 'est' value) + #Content.V2
I though about pulling the #Content.EntityId to set some dynamic var names like:
<input type="text" id="#Content.EntityId-newfield"">
and pulling some <script>get the myResult again, add #Content.V2, set document.getElementById('#Content.EntityId-newfield').value</script> inside the loop but it doesn't work.
How can I achieve this?
Here's the full page:
<h1>My page</h1>
<br>
idd: <input type="text" id="idd" oninput="calculate()"> __ est: <input type="text" id="est">
<br><br>
<table border="1">
<thead>
<tr>
<th></th>
<th>Id</th>
<th>Title</th>
<th>V1</th>
<th>V2</th>
<th>V1 / V2</th>
<th>Field I know not how to calculate</th>
</tr>
</thead>
<tbody>
#foreach(var Content in AsDynamic(Data["Default"])){
<tr>
<td>#Edit.Toolbar(Content, actions: "edit,replace")</td>
<td>#Content.EntityId</td>
<td>#Content.Title</td>
<td>#Content.V1</td>
<td>#Content.V2</td>
<td>#Math.Round(#Content.V1 / #Content.V2, 2)</td>
<td>This should be the myResult var (or 'est' value) + #Content.V2</td>
</tr>
}
</tbody>
</table>
<script>
function calculate() {
var idade = document.getElementById('idd').value;
var myResult = (parseInt(idade) + 4) * 2;
document.getElementById('est').value = myResult;
}
</script>
Figure an array of functions would do the trick.
Before #foreach:
var arrayOfFunctions = [];
<input type="text" id="peso" oninput="callFunctions()">
inside #foreach:
arrayOfFunctions.push(function(setPeso) { document.getElementById('#Content.EntityId').value = setPeso * #Content.fieldToCalculate; });
after: #foreach:
function callFunctions() {
var myPeso = parseInt(document.getElementById('peso').value);
arrayOfFunctions.forEach(f => f(myPeso));
}

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!

javascript redirection only on second try

I wrote a little "webpage" to start streams on my xbmc with jsonrpc. Now the problem I am facing is that i always have to send the form request twice to make it work. could it be that I am using the window.open function wrong? or am I missing something?
<html>
<body>
<head>
<script type="text/javascript">
function postFunction() { // inside script tags
var vForm = document.getElementById("frmGui");
var vStrServer = "";
var vStrFile = "";
var vStrPost = "http://";
vStrServer = vForm.idServer.value;
vStrFile = vForm.idFile.value;
vStrPost += vStrServer+"/jsonrpc?request={\"jsonrpc\":\"2.0\", ";
vStrPost += "\"id\":0, \"method\": \"Player.Open\", \"params\":{\"item\""
vStrPost += ":{\"file\":\""+vStrFile+"\"}}}";
window.open(vStrPost,"_self");
}
</script>
</head>
<table>
<tr>
<form id="frmGui" name="gui" action="#" onSubmit="postFunction(this)" methode="POST">
<td><input id="idServer" name="server" type="text" value="IP_ADRESS"/></td>
</tr>
<tr>
<td><input id="idFile" name="file" type="text"/></td>
</tr>
<tr>
<td><input type="submit"/></td>
</tr>
</form>
</table>
</body>
</html>
Try to put it into window.onload(cb).
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload
Why you passed argument whene you call postFunction() ? it has not argument upon decliration right way is
<form id="frmGui" name="gui" action="#" onSubmit="postFunction()" methode="POST">
remove this inside postFunction brace

JavaScript Functions & Equations

I'm trying to complete a simple multiplication problem of an input and a number already there (5.49) using JavaScript and the Compute function. I have it inside of a table and am using internal css for the structure of the page.
My problem is the when I press the compute button on the page, the answer to the equation (input)*5.49 doesn't come up, but instead nothing does. I'm struggling to find mistake.
Additional Notes: I've already checked to see if the compute button was working by replacing the formula with a pop-up box and it was working.
<!DOCTYPE html>
<html>
<head>
<title>Project</title>
<style type="text" /css>
.inbox { width=30px; text-align: right; border: 2px solid black; } .align { text-align: right }
</style>
<script type="text/javascript">
function compute() {
var a = form1.inputA.value;
a = parseFloat(a);
var b = form1.inputB.value;
b = parseFloat(b);
var c = form1.inputC.value;
c = parseFloat(c);
var e = a * 5.49;
form1.sumA.value = e.toFixed(2);
}
function pageInit() {
form1.inputA.focus();
}
</script>
</head>
<body onload="pageInit();">
<form id="form1">
<table border="2">
<tr>
<th colspan="4">Sample Order Form</th>
</tr>
<tr>
<th>Quantity</th>
<th>item</th>
<th>Unit Price</th>
<th>Totals</th>
</tr>
<tr>
<th>
<input tabindex="1" class="inbox" type="text" id="inputA" />
</th>
<th>Apples</th>
<td>$5.49</td>
<th>
<input class="inbox" type="text" id="sumA" readonly="readonly" />
</th>
</tr>
<tr>
<th>
<input tabindex="4" type="button" value="Compute" onclick="compute();" />
</th>
</tr>
</table>
</form>
</body>
</html>
The fields inputB and inputC just don't exist. Then it produce an error.
function compute() {
var a = form1.inputA.value;
a = parseFloat(a);
var e = a * 5.49;
form1.sumA.value = e.toFixed(2);
}
You can use web developer tools to analyze your code.
Modern web browser have tools like that.
Take a look at google chrome developer tools : https://developer.chrome.com/devtools for example. You can find equivalent tools for firefox and Internet Explorer.

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