Problems converting a NaN value in Javascript - javascript

I'd just started learning Javascript and one of my first projects is to build a site that gets values from an input box and use them to get the area of a circle but I keep getting NaN as a result
My code looks like this:
let circle = document.getElementById("rCircle");
let radius = circle.value;
const calcAreaCircle = (radius) => {
let circleResult = Math.PI * Math.pow(radius, 2);
circleArea.innerHTML = ("The area is: " + circleResult)
};
Additional info - I have already tried converting the NaN using parseInt as let radius = parseInt(circle.value). Also I keep getting NaN in the console unless the code is wrapped in a window.onload function.
Does anybody know what am I missing??
*Edit
This is part of my html
<div class="imageContainer">
<h4>Circles</h4>
<div class="Figures"><img src="assets/circle-shape-outline.png" alt="Circle image"></div>
<div class="text">
<p>Tell me the radius</p>
<input type="number" name="" value="" placeholder="Raduis" id="rCircle">
<button id="calcCircle">Get area</button>
</div>
<p id="circleArea"></p>
</div>

function check() {
let circle = document.getElementById("rCircle");
let circleArea = document.getElementById("circleArea");
let radius = circle.value;
let circleResult = Math.PI * Math.pow(parseInt(radius), 2);
circleArea.innerHTML = ("The area is: " + circleResult)
}
<div class="imageContainer">
<h4>Circles</h4>
<div class="Figures"><img src="assets/circle-shape-outline.png" alt="Circle image"></div>
<div class="text">
<p>Tell me the radius</p>
<input type="number" name="" value="" placeholder="Raduis" id="rCircle">
<button id="calcCircle" onclick="check()">Get area</button>
</div>
<p id="circleArea"></p>
</div>

Have you tried parseInt with second param "null"?
parseInt(circle.value, null);

I have tested your code that the input value can be get inside the function. I have modified the code and is working fine for me. You may also want to make use of number input type to avoid parsing. In case of string number, the javascript will automatically convert it into number. You can check that by removing parsing.
<!Doctype HTML>
<html>
<body>
Enter Value: <input type="number" id='rCircle'>&nbsp
<button onclick="calcAreaCircle()">Calculate</button>
<br/>
<br/>
<span id="circleArea"></span>
<script>
var calcAreaCircle = function(){
var circle = document.getElementById("rCircle"),
circleArea = document.getElementById("circleArea");
radius = parseInt(circle.value,10);
console.log(parseInt(circle.value,10));
console.log(typeof radius+": "+radius);
var circleResult = Math.PI * Math.pow(radius, 2);
circleArea.innerHTML = ("The area is: " + circleResult)
};
</script>
</body>
</html>

make sure, you get correct value from input with id="rCircle"

As you said that your code is working fine after wrapping in window.onload it means that in normal case DOM loading is not finished before you called document.getElementById("rCircle").
Important thing is that how you are binding your JS code. You can check the DOM loading part of your input box by this:-
if(document.getElementById("rCircle").length > 0)
{
// Your JS Code like as
// let circle = document.getElementById("rCircle");
// let radius = circle.value;
// etc
}
else
{
// DOM is not loaded , ouu need to wait for DOM loading completion
}
or you can call the function manually and in thac case your DOM will be finished with loading -
HTML Code
<div class="imageContainer">
<h4>Circles</h4>
<div class="Figures"><img src="assets/circle-shape-outline.png" alt="Circle image"></div>
<div class="text">
<p>Tell me the radius</p>
<input type="number" name="" value="" placeholder="Raduis" id="rCircle">
<button id="calcCircle" onClick="getArea()">Get area</button>
</div>
<p id="circleArea"></p>
</div>
JS Code
<script>
function getArea(){
var circle = document.getElementById("rCircle"),
circleArea = document.getElementById("circleArea");
radius = parseInt(circle.value);
var circleResult = Math.PI * Math.pow(radius, 2);
circleArea.innerHTML = ("The area is: " + circleResult)
};
</script>

Related

HTML functions don't return value when click on button

I wrote the code provided. But on clicking the button, nothing appears.
function calculate() {
var colony = document.getElementById("co").value;
var dilution = document.getElementById("dil").value;
var inoculum = document.getElementById("in").value;
var b = parseFloat(dilution) * parseFloat(inoculum);
var c = parseFloat(colony) / b;
if (!isNaN(c)) {
document.getElementById("multiplication").innerHTML = "the conentration is " + c;
}
}
<button type="button" onclick="calculate">Calculate</button>
<p id="multiplication"></p>
You didn't call calculate() function. It should be onclick="calculate()" not onclick="calculate".
There's no value property in an element. Use innerText property of an element.
function calculate() {
var colony = document.getElementById("co").innerText;
var dilution = document.getElementById("dil").innerText;
var inoculum = document.getElementById("in").innerText;
var b = parseFloat(dilution) * parseFloat(inoculum);
var c = parseFloat(colony) / b;
if (!isNaN(c)) {
document.getElementById("multiplication").innerHTML = "the conentration is " + c;
}
}
<button type="button" onclick="calculate()">Calculate</button>
<p id="multiplication"></p>
<div id="co">1</div>
<div id="dil">2</div>
<div id="in">4</div>
I have added the HTML, which wasn't provided in the shared code
and it works. It is permissible for input fields to not have an ID attribute.
Client Side:
function calculate() {
var colony = document.getElementById("co").value;
var dilution = document.getElementById("dil").value;
var inoculum = document.getElementById("in").value;
var b = parseFloat(dilution) * parseFloat(inoculum);
var c = parseFloat(colony) / b;
if (!isNaN(c)) {
document.getElementById("multiplication").innerHTML =
"the conentration is " + c;
}
}
HTML:
co: <input type="text" id="co"><br>
dil: <input type="text" id="dil"><br>
in: <input type="text" id="in"><br>
<button type="button" onclick="calculate()">Calculate</button>
<div id="multiplication">fff</div>
In your inital code, your onclick="calculate" was missing () after calculate.
I've added that as well as a script tag within your html with your JavaScript function without changing much of your original code's text.
Working Jsfiddle: https://jsfiddle.net/yuL58da1/
For presentation/educational purposes, I solved the problem using JQuery as well to show you what the solution would look like using JQuery.
Working JsFiddle: https://jsfiddle.net/4g9ayoqb/
Using the JQuery method, I've updated your html button to include a id attribute and removed onclick:
<button id="calculate" type="button">Calculate</button>
and added a JQuery click selector for that button's id:
$(document).on('click','#calculate',function()

How do I show the random item that was generated from a list?

Once the "randomSong" is generated, I want it to show a sentence below like the following:
Use the !code(my randomly generated code) command in our chat forums to redeem premium.
function findSong() {
var song = ["xikskx", "iwnujk", "ldilxb", "hgbhrw", "ijkczb"];
var random = Math.floor(Math.random() * (song.length - 1));
document.getElementById("randomSong").setAttribute("value", song[random]);
}
<div>
<button onclick="findSong();" type="randomSong">Generate Premium Code</button>
<input "RandomCode" id="randomSong">
</div>
You could add <p> element to your html code that would be used to display the newly generated text.
<div>
<button onclick="findSong();" type="randomSong">Generate Premium Code</button>
<input "RandomCode" id="randomSong">
<!-- new code -->
<p id="text"></p>
</div>
And then fill it on click like this.
function findSong() {
var song = ["xikskx", "iwnujk", "ldilxb", "hgbhrw", "ijkczb"];
var random = Math.floor(Math.random() * (song.length - 1));
document.getElementById("randomSong").setAttribute("value", song[random]);
// new code
var premium = document.getElementById('text');
premium.textContent = 'Use the code ' + song[random] + ' command in our chat forums to redeem premium.';
}
fiddle: https://jsfiddle.net/LLu75ksf/5/

Issues with javascript using html inputs as variables (Beginner!)

Hello Everyone!
Im having some issues with a simple calculator type website. My issue involves using a javascript function to calculate an equation using variables from an HTML input form.
Below is my javascript function, which is placed above the form in the HTML file.
var userName = document.getElementsByName("userName")[0].value;
var userMmr = document.getElementsByName("userMmr")[0].value;
var userDesmmr = document.getElementsByName("userDesmmr")[0].value;
var userWinrate = document.getElementsByName("userWinrate")[0].value;
function findshit(){
alert(userMmr.value);
var LR = 1.0 - userWinrate.value;
var GP = 1;
while (1){
var GW = GP * userWinrate.value;
var GL = GP * LR;
var MMRG = GW * 25;
var MMRL = GL * 25;
var TMG = MMRG - MMRL;
if (TMG + userMmr.value >= userDesmmr.value) {
alert("Congrats! it will take you " + String(GP));
} else {
GP += 1;
}
}
}
<h2>Enter your information below</h2>
</br>
<form>
What's your name?:<br>
<input type="text" name="userName" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current mmr?:<br>
<input type="text" name="userMmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your desired mmr?:<br>
<input type="text" name="userDesmmr" onkeyup="findshit();" onchange="findshit();"/><br>
</br>
What's your current win rate?<br>(put in decimal form eg. 50% = .50):<br>
<input type="text" name="userWinrate" onkeyup="findshit();" onchange="findshit();"/"><br>
<br>
<button onclick="findshit();">Try it</button>
Don't use .value when you set all the variables at the top. The code in the function expects those variables to just be the elements, because it uses .value to get their updated values. So it should just be:
var userName = document.getElementsByName("userName")[0];
var userMmr = document.getElementsByName("userMmr")[0];
var userDesmmr = document.getElementsByName("userDesmmr")[0];
var userWinrate = document.getElementsByName("userWinrate")[0];
You also need to put the script after the HTML, or put all the code inside the window.onload function. If you run the script before the HTML is loaded, none of the document.getElementsByName() calls will find the elements.
You should remove or modify while (1) loop. Because it is an infinite loop. I think you should use If loop in the scenario.

Why is JavaScript correctly calculating my variable yet displays it as undefined in the HTML?

And how do I get it to display the number, not undefined?
It's a tipping app. The user inputs the price of whatever it is they bought (pizza, haircut, etc.) in #price, then calcTip() calculates the tip, sends it over to calcTotal() which calculates the total, and sends it over to displayAmounts().
I don't know exactly what happens, but something messes up with the variable tip. calcTip() works correctly and calculates the tip amount successfully. I know this because the JavaScript console displays the amount when I input tip;. However, on the page, #tipSpan displays the tip as undefined.
What baffles me most is that the variable total works perfectly fine.
Does anyone know what might be going on or how I can fix it?
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tipping App</title>
<style>
<!-- Temporary -->
#error {
display: none;
}
</style>
</head>
<body>
<div id="wrapper">
<header>
<h1>Tipping App</h1>
</header>
<section>
<div class="price">
<h2>Price Information</h2>
<label for="priceInput">Enter the price below!</label><input id="priceInput" type="text"><button id="calcButton">Calculate the Tip</button>
<p id="error">Error: You need to enter the cost!<br><br>Use only numbers and decimal points, no currency symbols or letters.</p>
</div>
<div id="tipContainer" class="tip">
<h2>Tip Information</h2>
<p id="tipPara">Your tip should be... <span>$<span id="tipSpan"></span></span></p>
</div>
<div id="totalContainer" class="total">
<h2>Total Information</h2>
<p id="totalPara">Your total is... <span>$<span id="totalSpan"></span></span></p>
</div>
</section>
</div>
<script src="js/app.js"></script>
</body>
</html>
Here is the JavaScript:
///// VARIABLES
//////////////////////////////
var priceInput = document.getElementById("priceInput");
var calcButton = document.getElementById("calcButton");
var error = document.getElementById("error");
var tipContainer = document.getElementById("tipContainer");
var tipPara = document.getElementById("tipPara");
var tipSpan = document.getElementById("tipSpan");
var totalContainer = document.getElementById("totalContainer");
var totalPara = document.getElementById("totalPara");
var totalSpan = document.getElementById("totalSpan");
var tip;
var total;
///// FUNCTIONS
//////////////////////////////
function calcTip() {
var price = priceInput.value; // This is the price the user inputs
var minTip = (Math.ceil(price * .15)); // Calculates a 15% tip rounded up to the nearest dollar
var maxTip = (price * .2); // Calculates a 20% tip
if (isNaN(price) || price === "") {
// If the user doesn't enter a number
// Or doesn't enter anything,
// Then display the error message
error.style.display = "block";
return;
} else {
error.style.display = "none";
if (maxTip < minTip) {
// If the 20% tip is less than the 15% rounded tip,
// Then let's go with that 20% tip
calcTotal(price, maxTip);
tip = maxTip;
} else {
// Otherwise, let's just do the 15%
calcTotal(price, minTip);
tip = minTip;
};
};
};
function calcTotal(price, tip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(tip);
total = (price + tip);
displayAmounts();
}
function displayAmounts() {
// Update the page to display the tip and the total to the user
tipContainer.style.display = "block";
totalContainer.style.display = "block";
tipSpan.innerText = tip;
totalSpan.innerText = total;
}
///// EVENTS
//////////////////////////////
calcButton.addEventListener("click", calcTip);
Also, unrelated, but does my JavaScript look good? Is it clean code? I hope to find a web development job in the near future, and I know I need to be good at JavaScript.
WORKING DEMO
Update the function arguments
function calcTotal(price, maxTip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(maxTip);
total = (price + tip);
displayAmounts();
}
Here the argument tip is overriding the global variable. Replace it to maxTip as you call.
1) In function displayAmounts, pass parameters tip & total
2) Instead of
tipSpan.innerText = tip,
TRY WITH
tipSpan.innerHTML = tip;
and same for total ,
use totalSpan.innerHTML = total
instead of
totalSpan.innerText ;
Then it should work
Try changing your method definition so it passes the values in:
displayAmounts(); should become displayAmounts(tip, total);
See the fiddle here.
Also you should use parseFloat rather than parseInt assuming you'll want to be more accurate than whole numbers.
Just a small mistake!
Instead of:
calcTotal(price, minTip);
tip = minTip;
Do:
tip = minTip;
calcTotal(price, minTip);
This way tip is calculated before displayAmounts is run.
Abut your code:
This is fine with just getting started. I recommend going through w3school's tutorials on javascript. The more you use javascript, the better you will get.
If you want a learning path I would recommend taking, let me know.
innerText works only on IE. textContent is W3C-compliant, but if you want your code to be standards compliant and cross-browser safe you should use this:
while( tipSpan.firstChild ) {
tipSpan.removeChild( tipSpan.firstChild );
}
tipSpan.appendChild( document.createTextNode(tip) );
Do this for totalSpan also.

Get value of span element and output it

Ok, I am more than impressed that you guys took your time to answer this, thank you so much, I did not expect it. Hope well follows you.
To explain my problem, I used that fiddle tool you all had. This is the code I have:
enter code here
http://jsfiddle.net/5xzSy/1/
-What I need, is to sum up the values that get calculated in the spans : budgetI + actualI
Modified your code to : Use .text() to populate the Span and assign some value to your inputs..(Since you have used jQuery)
http://jsfiddle.net/xubam99v/
HTML Code
<pre>
<input id=primaryB type="text" value="100"></input><input id=primaryA type="text" value="100"></input><span id=primary></span><br />
<input id=spouseB type="text" value="100"></input><input id=spouseA type="text" value="100"></input><span id=spouse></span><br />
Budget: <span id=budget></span> <br />
Actual: <span id=actual></span><br />
</pre>
Javascript/jQuery Code
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').text(primaryBValue + spouseBValue);
$('#actual').text(primaryAValue + spouseAValue);
listen on the change-event to sum numbers after you insert then
http://jsfiddle.net/55c5uqhc/2/
$('#primaryB,#primaryA,#spouseB,#spouseA').change(calc);
function calc() {
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#primary').html(primaryBValue + primaryAValue);
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
$('#spouse').html(spouseBValue + spouseAValue);
$('#budget').html(primaryBValue + spouseBValue);
$('#actual').html(primaryAValue + spouseAValue) ;
}
You need to create a trigger upon which you populate the <span>s, also use text() instead oh html()
Here's example(probably a bad one but it's good place to start):
function:
$('input').keyup(function(e){
var spouseBValue = parseFloat($('#spouseB').val());
var spouseAValue = parseFloat($('#spouseA').val());
var primaryBValue = parseFloat($('#primaryB').val());
var primaryAValue = parseFloat($('#primaryA').val());
$('#spouse').text(spouseBValue - (-spouseAValue));
$('#primary').text(primaryBValue - (-primaryAValue));
$('#budget').text(primaryBValue - (-spouseBValue));
$('#actual').text(primaryAValue - (-spouseAValue));
});
fiddle

Categories

Resources