So I have this form that is performing very basic calculations and when I submit it, it results to NaN.
The thing that is confusing me is when I do a typeof of one of the variables assigned to the value of each input, it returns "number", and yet I get NaN as a result. Can anyone tell me why or what it is I am doing wrong?
Here's my HTML:
<form name="baddiesCost">
<input type="number" placeholder="Total Caught" name="goomba" id="goomba-form">
<input type="number" placeholder="Total Caught" name="bobombs" id="bob-ombs-form">
<input type="number" placeholder="Total Caught" name="cheepCheeps" id="cheep-form">
<button id="submitForm">Submit</button>
</form>
<h1 id="total"></h1>
Here's my JavaScript:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
This statement document.baddiesCost.bobombs.value * bobombsCost; uses variable bobombsCost which is not defined at this time.
So, it is similar to: document.baddiesCost.bobombs.value * undefined; which will be NaN.
To solve this put variable inicialization before usage like in following code:
document.baddiesCost.addEventListener("submit", function(e) {
e.preventDefault();
var goombaCost = 5;
var bobombsCost = 7;
var cheepCost = 11;
var goombaCaught = document.baddiesCost.goomba.value * goombaCost;
var bobombsCaught = document.baddiesCost.bobombs.value * bobombsCost;
var cheepsCaught = document.baddiesCost.cheepCheeps.value * cheepCost;
var showTotal = document.getElementById("total");
var total = goombaCaught + bobombsCaught + cheepsCaught;
showTotal.textContent = cheepsCaught;
console.log(bobombsCaught);
console.log(typeof bobombsCaught);
})
Anyway, NaN is number type, you can refer to following post for more explaination.
Related
I'm working on creating a website that can translate a base 10 number into Binary for extra credit in a class I am taking.
My website URL is: http://loganf.tynken.com. My goal is to have the user enter a number into a form, for that number to become a string in a <h4> tag, and to be used by JavaScript to take the string, make it a number, and to then use more code to show the binary number on the screen.
I'm having trouble getting the string into a number.
The JavaScript shown here is now my final product, but a way to try to make the number appear.
var base10, base2, v2_0, v2_1, v2_2, v2_3, v2_4, v2_5, v2_6, v2_7,
v2_8, v2_9, v2_10, v2_11, v2_12;
base10 = document.getElementById('base10');
base2 = document.getElementById('base2');
v2_0 = 1;
v2_1 = 2;
v2_2 = 4;
v2_3 = 8;
function assignvarbinaryvalue() {
var binaryNumber = Number(base10);
var newEl = document.createElement('h4');
var newText = document.createTextNode(binaryNumber);
newEl.appendChild(newText);
var position = document.getElementById('binaryID');
position.appendChild(newEl);
}
<h1>Binary Translator</h1>
<p><div id="base10"><?php echo $_GET['base10']; ?></div><p id="binaryID"></p></p>
var base10 = document.getElementById('base10');
var base2 = document.getElementById('base2');
document.getElementById('submit').onclick=function() {
var number=parseInt(base10.value);
base2.value=decimalToBinary(number);
}
function decimalToBinary(n){
var binaryNumberStr = "";
var binaryNumber=0;
var step=0;
while (Math.pow(2, step)<n)
{
step+=1;
}
for(var i=step; i>=0; i--){
var c=Math.floor(n/Math.pow(2, i))
n-=Math.pow(2, i)*c;
binaryNumber+=Math.pow(2, i)*c;
binaryNumberStr+=c;
}
//binaryNumberStr+=(n-binaryNumber)
return binaryNumberStr;
}
<p>Number:</p>
<input type="text" id="base10" name="base10" size="15" maxlength="30">
<input type="submit" id="submit" name="submit" value="submit">
<input type="text" id="base2" name="base2" disabled size="15" maxlength="30">
If you want to convert string into number you can just use javascript function
parseInt()
You are not grabbing the value:
var base10, base2, v2_0, v2_1, v2_2, v2_3, v2_4, v2_5, v2_6, v2_7, v2_8, v2_9, v2_10, v2_11, v2_12;
base10 = document.getElementById('base10');
base2 = document.getElementById('base2');
v2_0 = 1;
v2_1 = 2;
v2_2 = 4;
v2_3 = 8;
v2_4 = 16;
//v2_5 = 32;
//v2_6 = 64;
//v2_7 = 128;
//v2_8 = 256;
//v2_9 = 512;
//v2_10 = 1024;
//v2_11 = 2084;
//v2_12 = 4096;
function assignvarbinaryvalue() {
var binaryNumber = parseInt(base10.innerHTML);
var newEl = document.createElement('h4');
var newText = document.createTextNode(binaryNumber);
newEl.appendChild(newText);
var position = document.getElementById('binaryID');
position.appendChild(newEl);
}
assignvarbinaryvalue()
I am completing the 57 programming exercises book by Brian P. Hogan.
With most of these exercises, I've tried to develop a GUI.
In the following exercise, I want to calculate the Simple Interest of a Principal value over a period of years. Simply put:
var yearlyInterest = Principal * (Percentage(whole number) /= 100)
(yearlyInterest * numberOfYears) + Principal
// outputs total amount at the end of investment over a period of however many years
As you can see in the example above, there are three core inputs - Principal, Percentage and Time.
When creating the graphical user interface, I am struggling to get all of these core inputs to calculate the result simultaneously.
The following code only manages to calculate the result once I enter the number for the Time input. (excuse my poor coding skills i.e. global variables, I'm only up to exercise 12!)
HTML
<!DOCTYPE html>
<html lang="en">
<body>
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;">
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;">
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;">
<div id="result"></div>
</body>
<script src="simpleInterest.js"></script>
</html>
JS
var principal = document.getElementsByClassName("principal");
var percentage = document.getElementsByClassName("percentage");
var time = document.getElementsByClassName("time");
var output = document.querySelector("#result");
var result;
var newResult;
var finalOutput;
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
var newPrincipal = principal[0].value;
result = newPrincipal;
}
if ( event.target.classList.contains( 'percentage' ) ) {
var newPercentage = percentage[0].value;
newResult = result * (newPercentage / 100);
}
if ( event.target.classList.contains( 'time' ) ) {
var newTime = time[0].value;
finalOutput = (newResult * newTime) + Number(result);
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
Could somebody please show me an effective way to simultaneously calculate something based on each input event and output it using the .innerHTML method?
Thanks!
You need to get the values of all the inputs, not just the one that the user is currently typing in. Define a single function that does this, and add it as an event listener for all 3 inputs.
var principal = document.querySelector(".principal");
var percentage = document.querySelector(".percentage");
var time = document.querySelector(".time");
var output = document.querySelector("#result");
function calcInterest() {
var newPrincipal = parseFloat(principal.value);
var newPercentage = parseFloat(percentage.value);
var newTime = parseFloat(time.value);
if (!isNaN(newPrincipal) && !isNaN(newPercentage) && !isNaN(newTime)) {
var result = newPrincipal + newTime * newPrincipal * newPercentage / 100;
output.textContent = result;
}
}
principal.addEventListener("input", calcInterest);
percentage.addEventListener("input", calcInterest);
time.addEventListener("input", calcInterest);
<label for="principal">Principal</label>
<input type="number" class="principal" style="border-color: black;"><br>
<label for="percentage">Percentage</label>
<input type="number" class="percentage" style="border-color: black;"><br>
<label for="time">Time</label>
<input type="number" class="time" style="border-color: black;"><br> Result:
<div id="result"></div>
Create function to calculate, and call this function instead of just executing some code. Something like that:
var principal = document.getElementsByClassName("principal")
var percentage = document.getElementsByClassName("percentage")
var time = document.getElementsByClassName("time")
var output = document.querySelector("#result")
var result
var newResult
var finalOutput
var calculate = () => {
var newPrincipal = principal[0].value;
result = newPrincipal
var newPercentage = percentage[0].value
newResult = result * (newPercentage / 100)
var newTime = time[0].value
finalOutput = (newResult * newTime) + Number(result)
}
document.addEventListener('input', function (event) {
if ( event.target.classList.contains( 'principal' ) ) {
calculate();
}
if ( event.target.classList.contains( 'percentage' ) ) {
calculate();
}
if ( event.target.classList.contains( 'time' ) ) {
calculate();
}
output.innerHTML = `${finalOutput ? finalOutput : ""}`
}, false);
I just want to get the square root of total2 .. but it won't appear in the selected box ..
here is the javascript codes.
i'll comment the html codes.
function myFunction() {
var q1 = document.getElementById("qinput1").value;
var q2 = document.getElementById("qinput2").value;
var q3 = document.getElementById("qinput3").value;
var total = parseInt(q1) + parseInt(q2) + parseInt(q3);
document.getElementById("ainput3").value=total;
var a1 = document.getElementById("ainput1").value;
var a2 = document.getElementById("ainput2").value;
//from the total we got, lets assign it a variable for further calculation
var a3 = document.getElementById("ainput3").value=total;
var total2 = parseInt(a1)*parseInt(a2)/ parseInt(a3);
document.getElementById("ansA").value = total2;
var total3 = math.sqrt(parseInt(total2));
document.getElementById("sqaureD").value = total3;
}
function myShapes() {
document.getElementById('squareA').style.display =
document.getElementById('shapes').value == 'Square' ? 'block' : 'none'
}
<form action="" id="fcalculation">
<fieldset>
<legend>Calculation of qu</legend>
<label><i>Ultimate bearing capacity</i> <b>(qu) = </b></label>
<input id="qinput1" type="text" placeholder="c'NcFcsFcdFci"/> +
<input id="qinput2" type="text" placeholder="qNqFqsFqdFqi"/> +
<input id="qinput3" type="text" placeholder="½βγNFγsFγdFγi"/>
</fieldset>
</form>
it seems that the calculation part at the very end is not working. sorry its my first time to code.
Classname is Math not math
Try replacing
var total3 = math.sqrt(parseInt(total2,10));
with
var total3 = Math.sqrt(parseInt(total2,10));
Also, looking at your markup, there are no fields with id ainput1, ainput2 and ainput3.
I am facing some problems arrays in php,,
<input class="form-control" placeholder="Start Time"
value="'.date("H.i").'" type="text" name="starttime[]" id="starttime"/>
</div>
<div class="col-lg-4">
<input class="form-control" name="endtime[]" id="endtime" onchange="myfunction1()" value="00.00" type="text" placeholder="End Time">
This is my ajax code and when I change end time It must be show other text box
<input class="form-control" name="kmcost" id="exkms" type="text" placeholder="Cost">
But single entry working but second entry(array) Not woeking my javascript code is here please help me..
my javascript is here..
function myfunction1()
{
var ftime = document.getElementById("starttime").value;
var etime = document.getElementById("endtime").value;
var timeanswer = etime - ftime;
var localtottme = document.getElementById("textbox3").value;
if(timeanswer > 8)
{
var totextme = timeanswer-8;
}
var exkms = document.getElementById('exkms');
exkms.value=totextme;
}
Try this:
function myfunction1()
{
// fetch value of element as string, x2
var ftime = document.getElementById("starttime").value;
var etime = document.getElementById("endtime").value;
// fetch hour as string, then convert to integer, x2
ftime = parseInt(ftime.split(':')[0]);
etime = parseInt(etime.split(':')[0]);
// calculate hour difference, initialize remainder variable to 0
var hourDifference = etime - ftime;
var eightHourRemainder = 0;
// check if hour difference is more than 8, if so then calculate remainder variable
var localtottme = document.getElementById("textbox3").value;
if(hourDifference > 8)
{
eightHourRemainder = hourDifference - 8;
}
// set element value to remainder variable
var exkms = document.getElementById('exkms');
exkms.value=eightHourRemainder;
}
I'm having trouble getting this bit of javascript to work. Whenever I try it inputs nothing into my div. It just adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL.
<h2>How small must you be to become a black hole?</h2>
<form name="form1">
<input id="howMuch" type="number" name="weight" placeholder="How much do you weigh?">
<input type="radio" name="measure" value="lbs" checked="true">lbs
<input type="radio" name="measure" value="kgs">kgs
<input type="submit" name="submit" value="Submit" onClick="calc(); return false;">
</form>
<br/>
<div id="insert"><div/>
<script language="JavaScript" type="Text/JavaScript">
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.form1.weight.value;
var measure = document.form1.measure.value;
measure = measure.trim();
if (measure !== "kgs"){
weight *= 0.4536;
}
finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}
</script>
Without the .trim() function, it executes perfectly, except for the fact that it will not recognize measure equaling anything resembling 'lbs' or 'kgs'. What is happening here?
Here: http://jsfiddle.net/dJJjr/1/
function calc() {
var speedOfLight = 299792458.0;
var gravityConstantYoctometre = 66738400000000.0;
var finalHeight = 0.0;
var weight = document.getElementById("howMuch").value;
var radio = document.getElementsByName('measure');
var measure = ""
for(var i =0; i< radio.length; i++)
{
if(radio[i].checked)
measure = radio[i].value;
}
measure = measure.trim();
alert(measure); //For testing purpose
alert(weight); //For testing purpose
if (measure !== "kgs"){
weight *= 0.4536;
}
finalHeight = (4.0 * gravityConstantYoctometre * weight)/Math.pow(speedOfLight,2);
finalHeight = (finalHeight).toFixed(5);
var message = '<em>You would have to be ' + finalHeight + ' yoctometres (1 metre x 10<sup>-24</sup>) tall before you would become a black hole.</em>';
document.getElementById('insert').innerHTML = message;
}