New to JS, Can't Fix Errors With School Project - javascript

I'm working on a project for a computers class, and am new to JavaScript. I keep getting NaN for output, and have looked for answers and haven't found any. (Project is a compound interest calculator and UI design is done.)
I'm not really sure what to try, cause I'm a JS newbie.
var i = getNumber("amountInput");
var c = getNumber("compoundedInput");
var l = getNumber("lengthInput");
var r = getNumber("rateInput");
var rc = r / c;
var cl = c * l;
onEvent("calculateButton", "click", function() {
var rca = 1 + rc;
var p = Math.pow(rca, cl);
var f = i * p;
setText("outputArea", f);
});
Output should be a number, but I am getting NaN.

You need to set all the variables inside the onEvent function, so that you get the values of the inputs after the user clicks the button. You're setting them when the page is first loaded, and the inputs will be empty at that time.
onEvent("calculateButton", "click", function() {
var i = getNumber("amountInput");
var c = getNumber("compoundedInput");
var l = getNumber("lengthInput");
var r = getNumber("rateInput");
var rc = r / c;
var cl = c * l;
var rca = 1 + rc;
var p = Math.pow(rca, cl);
var f = i * p;
setText("outputArea", f);
});

NaN in JS means 'not a number'. (mdn reference)
Usually, you would see NaN when you're trying to convert a non-numeric string to a number, either explicitly (e.g. parseFloat('3')), or implicitly (e.g. the expression 3 * 'a' will implicitly try to convert 'a' to a number). Worth noting, dividing by zero does not give NaN in JS (it gives infinity or -infinity); however, 0/0 also gives NaN.
For your use case, you're expecting getNumber to return a numeric, but it seems like it isn't. Look at your getNumber code (or copy it in your question).

if you want to get number from input in html you cant use getNumber()
<input type="text" id="number" >
<button id="submit">Submit</button>
and for geting the number:
const number = documnet.getElementById('number');
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', () => {
const plusOne = 1 + Number(number.value);
console.log(plusOne)
});

Related

Getting 6.33 from an equation in Javascript when it should output 8.99

I'm doing some simple math in Javascript, but my equation's result is drastically different than what it should be. The math is:
3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1;
When I did it out by hand, and then used Wolfram Alpha (https://www.wolframalpha.com/) I get the correct result of 8.99. However, when I use the equation in Javascript I mysteriously get 6.33
The actual equation looks like
VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2;
but I removed all the variables in an attempt to debug (I thought it might be some error where I needed parseInt)
Here are the whole functions for reference
function calc(){
var temp = 0;
var total = 0;
for(i = 0; i<sArr.length; i++){
total = total + calc2(i);
}
var o = document.getElementById("output");
o.value = total;
}
function calc2(i){
var s = document.getElementById("s"+i);
var g = document.getElementById("g"+i);
var t = document.getElementById("t"+i);
var VO2walkmin = 3.28;
var VO2rest = 3.05;
var C1 = 0.32;
var C2 = 0.19;
var C3 = 2.66;
var Cdecline = 0.73;
var s2 = s.value;
var g2 = g.value;
var t2 = t.value;
var negGrade = g.value;
if(g2 < 0){g2 = 0};
//VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*s2^2)); //ORIGINAL TRANSCRIPTION
//VO2move = VO2rest+(((C1*g2)+VO2walkmin)+(1+(C2*g2))*(C3*s2^2))*t2; // TRANSLATED FROM COPY PASTE
VO2move = 3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1^2))*1; // COPY - PASTED FROM EXCEL
return VO2move;
}
Even naked numbers I still get the output of 6.33. I'm totally puzzled, and any help is appreciated.
You need to take the power (exponentiation) operator ** instead of the bitwise XOR operator ^.
console.log(3.05+(((0.32*0)+3.28)+(1+(0.19*0))*(2.66*1**2))*1);

javascript return units, if present when multiplying 2 numbers

2 numbers input to my function values are a, "0.045u" and b, "3"
function mult2nums(a,b) {
var c = null;
var unitsFora = null;
var unitsForb = null;
var cUnits = null;
//--> issue - unitsFora = ??; // how to strip off units designator
//--> issue - unitsForb = ??; // how to strip off units designator
a = isFloat(a); // also works if int
b = isFloat(b); //
c = a*b;
// add logic to compare unit designators and convert as needed
return(c+cUnits); // need to return the units, returns a string type
}
You can use regex to filter out the units:
function mult2nums(a,b) {
var c = null;
var cUnits = null;
var unitRegex = /[A-Za-z].*/g
var unitsForA = a.match(unitRegex);
var unitsForB = b.match(unitRegex);
a = parseFloat(a.replace(unitsForA, ''));
b = parseFloat(b.replace(unitsForB, ''));
c = a*b;
// add logic to compare unit designators and convert as needed
return c + cUnits;
}
Note that the code uses the first encounter of character as the start position of the unit. It can handle upper/lower case differences, and units with number in it (e.g. m/s^2). You can modify the code further to suit your specific needs.
jsFiddle sample:
https://jsfiddle.net/ywafx1be/

Want to get set value in javascript issue

I want my code to display 170, 122 . All the values have been set in Javascript but still I am not getting the output.
<!DOCTYPE html>
<html>
<body>
<button onclick="UidToPost()">Get It</button>
<script>
var SetUid1 = "170";
var SetUid2 = "122";
var SetUid3 = "135";
var SetUid4 = "144";
var c = 0;
var timingToSend;
var SetUid;
function UidToPost() {
c = c + 1;
var postTo = "SetUid" + c + "";
document.getElementById("do").innerHTML = postTo;
timingToSend = setTimeout('UidToPost()', 1000);
};
</script>
<p id="do"></p>
</body>
</html>
Thanks in advance.
This is the code that I am using
var SetUid = [ "170", "122", "135", "144" ];
var c = 0;
var timingToSend;
function UidToPost() {
var postTo = SetUid[c++];
document.getElementById("do").innerHTML = postTo;
if (c < SetUid.length)
timingToSend = setTimeout(UidToPost, 1000);
};
Use an array instead of discreet variables;
var SetUid = [ "170", "122", "135", "144" ];
var c = 0;
var timingToSend;
function UidToPost() {
var postTo = SetUid[c++];
document.getElementById("do").innerHTML = postTo;
if (c < SetUid.length)
timingToSend = setTimeout(UidToPost, 1000);
};
You're trying to dynamically create the name of the variable to use with string concatenation, which is possible but not with that syntax. Since your variables are global variables, they'll be stored in the window object, so you can access them like this:
window["SetUid1"]
window["setUid2"]
//etc
With that in mind, you'll simply need to change this line:
var postTo = "SetUid" + c + "";
to:
var postTo = window["SetUid" + c];
You'll also need to handle the case where that variable doesn't exist (i.e. they click the button again after the last variable has been displayed), and take appropriate action (probably cycle back to the beginning).
Here is a working demo.
document.getElementById("do").innerHTML = window[postTo];
You should also get in the habit of avoiding the string argument version of setTimeout as it can cause security issues:
timingToSend = setTimeout(UidToPost, 1000);
I presume you'll also want to call clearTimeout() (or avoid setting the last one in the first place), e.g., after your variables are finished.
Finally, this might have been done more easily and flexibly with an array, but the above is how you can do it with your current approach.
This will do the trick:
document.getElementById("do").innerHTML = window[postTo];
You still have to perform a check for the number of vars. Now after the 4th var is displayed, the function will now write "undefined" to the screen because you keep looping.
The reason this is not working, is that you're concatenating the string SetUid with the current count c to make a string, and adding that to the innerHTML of the div.
Instead, you should hold your values in an array and use your variable c as an index to that array:
var values = [170,122,135,144]
var c = -1;
var timingToSend;
var SetUid;
function UidToPost() {
c = (c + 1) % values.length;
var postTo = "SetUid" + c + "";
document.getElementById("do").innerHTML = values[c];
timingToSend = setTimeout('UidToPost()', 1000);
}
Live example: http://jsfiddle.net/RsKZj/

JQuery multiply and add

Let's say I have some numbers that I want to multiply and add.
var a = 5;
var b = 10;
var c = 2;
var d = 3;
I want to sum b and c then multiply that by a, then add d. Easy right?
If if were a normal equation the formula would look like: (a * (b + c) + d)
But how do I do that in JQuery?
(Note: the reason for JQuery is that I'll be getting these numbers from fields and divs... and placing a total elsewhere, etc.)
By default script language does not know type as int or float. So you can fix that by multiplying 1 to the value you expect to be a number.
var a = 5;
var b = 10;
var c = 2;
var d = 3;
var total = a*1 * (b*1 + c*1) + d*1;
convert your value into float or integer first before you do calculation. Example:
var a = parseFloat($(this).val());
var b = parseInt($("#b").attr("data"));
var c = (a+10)*b;
$("#result").text(c.toFixed(2));
Just store the values in variables before you apply them to the equation:
var a = +$("#input1")[0].value;
var b = +$("#input2")[0].value;
var c = +$("#input3")[0].value;
var d = +$("#input4")[0].value;
$("#output")[0].value = a*(b+c) + d;
The plus sign before the jquery function is there to force the string value into a Number value.
Correct JQuery is 100% javascript.
Although, worth mentioning just use parseint() for the values that you get from text field
You can still do the calculation using normal javascript, just refer to the contents using jQuery selectors if necessary.

Javascript How to define multiple variables on a single line?

Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.
If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?
var a = 0;
var b = 0;
Is it:
var a = b = 0;
or
var a = var b = 0;
etc...
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to #alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
An example would be:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];
There is no way to do it in one line with assignment as value.
var a = b = 0;
makes b global. A correct way (without leaking variables) is the slightly longer:
var a = 0, b = a;
which is useful in the case:
var a = <someLargeExpressionHere>, b = a, c = a, d = a;
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b, c and d on the window scope.
Here is the new ES6 method of declaration multiple variables in one line:
const person = { name: 'Prince', age: 22, id: 1 };
let {name, age, id} = person;
console.log(name);
console.log(age);
console.log(id);
* Your variable name and object index need be same
Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:
let [a, b, c, d] = Array(4).fill(0);
console.log(a, b, c, d);
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
do this if they have same value
let x = y = z = 0
otherwise
let [x, y, z] = [10, 30, 50]
console.log(x, y, z) // 10 30 50
The compressed type of that is here:
var a, b = a = "Hi";
& for 3 variables:
var x, y, z = x = y = "Hello";
Hope to be helpful!
This is completely correct:
var str1 = str2 = str3 = "value";
And if change one of their value, the value of other variables won't change:
var str1 = str2 = str3 = "value";
/* Changing value of str2 */
str2 = "Hi Web!";
document.write("str1 = " + str1 + " - str2 = " + str2 + " - str3 = " + str3);

Categories