script not producing result - javascript

New to javascript. Would very much like to produce a simple calculator that uses three inputs and 4 fixed values to produce and report a 'peak power output' value. Code is as follows:
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
html:
<td>
<input id="vj" type="text" oninput="calculate()" />
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" />
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" />
</td>
have this in a html page with table to display input and results, input works, but not results.

You have jquery tagged, so here is a jQuery version.
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = $('#vj').val();
hgt = $('#hgt').val();
wgt = $('#wgt').val();
result = $('#peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.val(peakresult);
}
$(document).ready(function() {
$('input[type="text"]').on('blur', function() {
calculate();
});
});
</script>
This assumes you also have <input type="text" id="peakresult" /> in your HTML.
I added a jQuery event handler that will call the calculate button when the user leaves the input field. That could be more useful than having a handler in the field tag.

if you replace
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
by
vj = Number(document.getElementById('vjump').value);
hgt = Number(document.getElementById('height').value);
wgt = Number(document.getElementById('weight').value);
It should work.
BUT WITH NO check for correct input.
(EDITED)
This following code is working (Tested on Chrome)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = Number(document.getElementById('vj').value);
hgt = Number(document.getElementById('hgt').value);
wgt = Number(document.getElementById('wgt').value);
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
</head>
<body>
<td>
<input id="vj" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="peakresult" type="text" value="0"/>
</td>
</body>

You can use unary plus, +, to turn your values into a number and then perform operations on them:
function add() {
var a = +document.getElementById('firstOperand').value;
var b = +document.getElementById('secondOperand').value;
return a + b;
}
Also your html suggests you are invoking the calculate function every keystroke by using oninput. You can use onblur to call the calculate function after the user leaves the field.

You might need parse text into integer
parseInt(val);
Check this live sample
http://jsfiddle.net/VdrWL/2/
Hope it helps.

Related

javascript format numbers from 8403.361344537816 to 8.403

I have a javascript to calculate taxes and it works like this
The html form
<td><input type="text" class="input-180" name="pbruto" id="pbruto" value="0"/></td>
<td><input type="text" class="input-180" name="pneto" id="pneto" value="0"></td>
<td><input type="text" class="input-180" name="piva" id="piva" value="0"></td>
The javascript code
<script>
var taxPerc = 1.19;
document.getElementById("pbruto")
.onkeyup = function(){
document.getElementById("pneto")
.value = parseFloat(document.getElementById("pbruto")
.value) * (1.00 / taxPerc)
document.getElementById("piva")
.value = parseFloat(document.getElementById("pbruto")
.value) - parseFloat(document.getElementById("pneto").value)
}
</script>
The problem is that the results I get from calculations are displayed like this
8403.361344537816
I need to get rid of those .361344537816 and format the number to 8.403 only
Any way to do this?
EDIT
No solutions yet
Lets say var x is holding the value, try:
x = parseInt(x) / 1000
It's easier to control the code, if you'd use variables instead of DOM to store values. I've re-written your code, and toLocaleString() method seems to do exactly what you want:
var taxPerc = 1.19;
document.getElementById("pbruto").addEventListener('input', function () {
var valNeto, valPiva,
elNeto = document.getElementById("pneto"),
elBruto = document.getElementById("pbruto"),
elPiva = document.getElementById("piva"),
valBruto = +(elBruto.value);
valNeto = valBruto * (1 / taxPerc);
valPiva = valBruto - valNeto;
elNeto.value = Math.round(valNeto).toLocaleString('de-DE');
elPiva.value = Math.round(valPiva).toLocaleString('de-DE');
});
label {
display: block;
}
<label>Bruto: <input id="pbruto" /></label>
<label>Neto: <input id="pneto" /></label>
<label>Piva: <input id="piva" /></label>

Can't invoke a function with js

Here is my html and js:
function calculateFun()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var c = document.getElementById('c').value;
var d = document.getElementById('d').value;
var e = document.getElementById('e').value;
var f = a*b;
document.getElementById('f').value = f;
var g = (f + (f*(d/100))).toFixed();
document.getElementById('g').value = g;
var h = ((1 -((a*c)/e))*100).toFixed();
document.getElementById('h').value = h;
}
<input type="number" id="a" onkeyup="calculateFun();" />
<input type="number" id="b" onkeyup="calculateFun();" />
<input type="number" id="c" value="100" />
<input type="number" id="d" value="50" />
<input type="number" id="e" onkeyup="calculateFun();" />
<br><br><p>******</p><br><br>
<input type="number" id="f" />
<input type="number" id="g" />
<input type="number" id="h" />
I tried this code in JSFIDDLE:
https://jsfiddle.net/1ex3b1sa/
but it is not working. also in my site, the function isn't invoked.
it is strange because, i can invoke other functions that i did, almost with the same way.
i tried changing to onclick, onkeypress or onkeydown, but can't see any results..
any ideas? maybe i have a typo? or maybe its a chrome problem?
In JSFiddle, you need to set your JavaScript wrap to "No wrap - in <head>" or else you'll get an "Uncaught ReferenceError: calculateFun is not defined" error.
Make sure that the function is here:
<html>
<head>
<script type="text/javascript">
function calculateFun() {
// ...
You could actually keep the function definition in the onLoad wrap and change:
function calculateFun() {
To this:
window.calculateFun = function() {
And it will work because you are adding your function as a static method to the browser's Window.
On the left side of jsfiddle.net is a box with "Frameworks & Extensions".
In the second select box you have to select:
No wrap - in <body>
or
No wrap - in <head>
Then it will work. If you dont do that the function will not be defind and it will run just once (in the OnLoad Event).
please learn jquery, its not that hard and will help you!
your fiddle in functioning jquery: https://jsfiddle.net/1ex3b1sa/3/
input-fields got class='calc'
and js:
$('.calc').keyup(function(){
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var d = $('#d').val();
var e = $('#e').val();
var f = a * b;
$('#f').val(f);
var g = (f + (f*(d/100))).toFixed();
$('#g').val(g);
var h = ((1 -((a*c)/e))*100).toFixed();
$('#h').val(h);
});

Change disabled output field to text with prefixt

My full code can be found here: http://pastebin.com/t3JCBRrX
I made an easy calculation script for my website. I'd like two modifications but I can't seem to do it.
This is what I have now:
The function:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').value = result;
}
The form:
<label for="e" id="answer">Kosten: </label>
<input type="field" name="Antwoord" id="e" disabled><br>
<input type="button" onclick="bereken()" value="Bereken">
I'd like to prefix the result with a euro sign (result is '€123' instead of '123').
I would also like the result to be just plain text, instead of a disabled input field.
Any help would be greatly appreciated, as I'm just a beginner. Thanks!
edit: the calculation is that complicated because I don't want the answer to be '1200' when '0' has been entered
See this FIDDLE
Just insert the value with '€' appended
document.getElementById('e').innerHTML = '€'+result;
Also you can change the disabled input to label if you want it to be plain text
var ap, result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken() {
setValue();
result = (((ap * 275) / (ap * 275)) * 1200 + (ap * 275) || 0).toFixed(e);
document.getElementById('e').innerHTML = '€' + result;
}
<input type='text' id='ap' placeholder='enter value' />
<label for="e" id="answer">Kosten:</label>
<label type="field" name="Antwoord" id="e" disabled></label> <br>
<input type="button" onclick="bereken()" value="Bereken">
change document.getElementById('e').value = result; to document.getElementById('e').value = "€"+result;.
change disabled to readonly.
Try this:
JS Code:
var ap,result;
function setValue() {
ap = Number(document.getElementById('ap').value);
}
function bereken(){
setValue();
result = (((ap*275)/(ap*275))*1200+(ap*275) || 0).toFixed(e);
document.getElementById('e').innerHTML = result;
}
HTML Code:
<input type="text" id="ap"/>
<label for="e" id="answer">Kosten: </label>
<span>€</span><span id="e"> </span><br>
<input type="button" onclick="bereken()" value="Bereken"/>

Javascript value of input

This is supposed to calculate circumference, however, I am only getting a zero returned. What am I doing wrong?
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
var Pi = 3.14159265;
var dia = document.getElementById("txtdia");
var circumf = dia * Pi;
function DisplayText(){
document.getElementById("txtcircumf").value = circumf;
}
</script>
</head>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" value="Change Text" onclick="DisplayText()"/>
</form>
</body>
</html>
The primary problem you have is that this script will run prior to your dom being ready. As a result, even if you were properly grabbing the diameter's value it still wouldn't work, since document.getElementById("txtdia") wouldn't return anything.
I would just fetch the diameter's value each time.
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
The other option of course is to put this entire script after your html. Ie
</body>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
There are 3 distinct issues which you need to fix for this to work correctly.
txtcircumf and textdia are the name of the elements, not the id, so using document.getElementById will fail.
Fix: Add that as an id onto the elements in question:
<input type="text" name="txtdia" id="txtdia" />
<input type="text" name="txtcircumf" id="txtcircumf" />
The elements are not present when the script first runs. This is the issue described by #AdamRakis and his fix is probably best - always retrieve the value when you need it:
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
A minor point, but when you read the .value of a field you get text, as you are doing a mathematical equation it is common practice to ensure the value you're wouking with is numeric. You can use parseFloat for this:
function DisplayText(){
var dia = parseFloat(document.getElementById("txtdia").value);
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
I made a couple structural changes that improve the overall quality of your code :) (see the arrows for changes)
<html>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" id="derp" value="Change Text" /> //<-- added ID, removed inline JS
</form>
<script type="text/javascript">
document.getElementById("derp").onclick = function() { //<-- use this style instead of inline onclicks!
var index = false;
var text = "This text shifts";
var dia = document.getElementById("txtdia").value; //<-- .value, not the whole element!
var circumf = dia * Math.PI; //<-- Math.PI is an object constant, very handy
document.getElementById("txtcircumf").value = circumf;
//no more standard function!
}
</script>
</body>
</html>

Trouble connecting javascript code to html code

I am creating a calculator and I have written the following code:
For javascript:
function calculate() {
'use strict';
var total;
var quantity = document.getElementById('quantity').value;
var price = document.getElementById('price').value;
var tax = document.getElementById('tax').value;
var discount = document.getElementById('discount').value;
total = quantity*price;
tax /= 100;
tax++;
total *= tax;
tax = tax/100;
tax = tax+1;
total = total*tax;
total -= discount;
document.getElementById('total').value = total;
return false;
}
function init() {
'use strict';
var theForm = document.getElementById('theForm');
theForm.onsubmit = calculate;
}
window.onload=init;
For html:
<div><label for="quantity">Quantity</label><input type="number"
name="quantity" id="quantity" value="1" min="1" required></div>
<div><label for="price">Price Per Unit</label><input type="text"
name="price" id="tax" value="1.00" required></div>
<div><label for="tax">Tax Rate (%)</label><input type="text"
name="tax" id="tax" value="0.0" required></div>
<div><label for ="discount">Discount</label><input type="text"
name="discount" id="discount" value="0.00" required></div>
<div><label for="total">Total</label><input type="text" name="total"
id="total" value="0.00"></div>
<div><input type="submit" value="Calculate" id="submit"></div>
I have saved the files respectively as shopping.js and shopping.html but I don't know how to interconnect the code together so that when I click on the shopping.html and the browser opens, the calculator works properly.
I have tried to include the javascript code in the html code by using the script tags but it didn't work. I read some articles that said you have to save them in the same directory, but I did not understand that. I saved them on my desktop in a file called shopping and I need some assistance from here.
Thank you.
Check here
The id for price was "tax" I think was just typo mistake. I changed also your input type sumbit to a button instead.
Code:
window.onload = function() { // this loads your script when the page loads
function calculate() {
'use strict';
var total = 0;
var quantity = document.getElementById('quantity').value;
var price = document.getElementById('price').value;
var tax = document.getElementById('tax').value;
var discount = document.getElementById('discount').value;
total = quantity * price;
tax /= 100;
tax++;
total *= tax;
tax = tax / 100;
tax = tax + 1;
total = total * tax;
total -= discount;
document.getElementById('total').value = total;
return false;
}
};
You can add this code to your page or call it by a external file, then you just need to put this in your html code <script src="shopping.js" type="text/javascript"></script>. Put inside the <head> or <body> tags.
If they're in the same directory, you can call the js file in your HTML page like so:
<script src="shopping.js" type="text/javascript"></script>
If it's in a folder you have to reflect that in the src line: foldername/filename
That's how to get an external js file into your HTML doc. However, if you're putting your js code directly into script tags on the HTML doc and it's still not working, then there's an issue with the code.

Categories