Javascript 'NaN' on calculate - javascript

I am new to javascript and trying to make a basic BMI calculator.
But I must be doing something wrong as it displays 'NaN' when I click on calculate.
Any ideas out there?
Thanks
<!DOCTYPE html>
<html>
<body>
<form>
Height: <input id="h" type="text" name="height"><br>
Weight: <input id="w" type="text" name="weight">
</form>
<button onclick="myFunction()">Calculate</button>
<p id="bmi"></p>
<script>
function myFunction()
{
var h;
var w;
var x=Math.round(w/(h*h));
var demoP=document.getElementById("bmi")
demoP.innerHTML="Your BMI is: " + x;
}
</script>
</body>
</html>

Try this:
function myFunction() {
var h = document.getElementById("h").value;
var w = document.getElementById("w").value;
var demoP = document.getElementById("bmi");
var x;
//checking are h and w numbers
if (isNaN(h) || isNaN(w)) {
x = 'Bad value';
} else {
x = Math.round(w/(h*h));
}
demoP.innerHTML="Your BMI is: " + x;
}

var h = document.getElementById("h").value;
var w = document.getElementById("w").value;
Please initialize value of h and w using above code.acknowledge user2110655

some changes:
var h = document.getElementById("h").value;
var w = document.getElementById("w").value;

Try this,
Added
var h = document.getElementById("h").value;
var w = document.getElementById("w").value;
Jaavscript:
function myFunction()
{
var h = document.getElementById("h").value;
var w = document.getElementById("w").value;
if((h!="" && isNaN(h)) && (w!="" && isNaN(w) ){
var x=Math.round(w/(h*h));
var demoP=document.getElementById("bmi");
demoP.innerHTML="Your BMI is: " + x;
}
}

var h;
var w;
var x=Math.round(w/(h*h));
h and w have not been initialized. hence X is not a number.

Try these vars :
var h = parseInt(document.getElementById('h').value());
var w = parseInt(document.getElementById('w').value());

Related

The second response is not displayed in JavaScript?

I enter 2 x and z coordinates. And the response should display 2 responses.
1 answer — Sum to the number 600. 2 answer - Difference from the number 600.
I have only entered one response, and then to the second script, not the first.
https://www.w3schools.com/code/tryit.asp?filename=GMFS5UGR7FWC
<!DOCTYPE html>
<html>
<body>
<script>
var x, y, c;
var outputText;
function validate() {
// get the input
x = document.forms["input_form"]["aterm1"].value;
y = document.forms["input_form"]["aterm2"].value;
// validate a, b and c
if (x == 0) {} else {
// calculate
var a1 = x;
var a2 = y;
var a3 = 600;
var a4 = (a1 +++ a3);
var a5 = (a2 +++ a3);
outputText = "<h>" + a4 + ", " + a5 + "</h> ";
}
// output the result (or errors)
document.getElementById("1").innerHTML = outputText;
}
</script>
<script>
var x, y, c;
var outputText;
function validate() {
// get the input
x = document.forms["input_form"]["aterm1"].value;
y = document.forms["input_form"]["aterm2"].value;
// validate a, b and c
if (x == 0) {} else {
// calculate
var a1 = x;
var a2 = y;
var a3 = 600;
var a4 = (a1 --- a3);
var a5 = (a2 --- a3);
outputText = "<h>" + a4 + ", " + a5 + "</h> ";
}
// output the result (or errors)
document.getElementById("2").innerHTML = outputText;
}
</script>
<h type="x">X</h>
<h type="z">Z</h>
<form name="input_form" action="javascript:validate();">
<input type="text1" name="aterm1" size="5" required>
<input type="text2" name="aterm2" size="5" required>
<input type="submit" value="Готово">
</form>
<p type="ygol1" id="1">Первый угол</p>
<p type="ygol2" id="2">Второй угол</p>
</div>
</body>
</html>
You can't have two functions with the same name. The second one will overwrite the first one. If you need to perform two calculations, use two functions and perhaps a parent function to call them both.
function validate() {
sum();
difference();
}
function sum() {
// calculate the sum
}
function difference() {
// calculate the difference
}
and then in your form you call validate() which is a weird name by the way, for a function that doesn't validate anything. Use good names for your functions so they do what they say, it makes your code easy to read.
<form name="input_form" action="javascript:validate();">
<!DOCTYPE html>
<html>
<body>
<h type="x">X</h>
<h type="z">Z</h>
<form name="input_form" action="javascript:validate();">
<input type="text1" name="aterm1" size="5" required>
<input type="text2" name="aterm2" size="5" required>
<input type="submit" value="Готово">
</form>
<p type="ygol1" id="1">Первый угол</p>
<p type="ygol2" id="2">Второй угол</p>
<script>
function validate() {
// get the input
var x = document.forms["input_form"]["aterm1"].value;
var y = document.forms["input_form"]["aterm2"].value;
// output the result (or errors)
document.getElementById("1").innerHTML = "<h>" + (x + 600) + ", " + (y + 600) + "</h>";
document.getElementById("2").innerHTML = "<h>" + (x - 600) + ", " + (y - 600) + "</h>";
}
</script>
</body>
</html>
https://www.w3schools.com/code/tryit.asp?filename=GMFZ3DNB6ELT

Loop through the sum of the two inputs until in doubled (javascript)

I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>

On mouse hover, display the corresponding sizes of bars, as mentioned in the input field

function draw() {
var nums = document.getElementById("number").value.split(",");
console.log(nums);
var w = 40;
var factor = 20;
var n_max = Math.max.apply(parseInt, nums);
var h_max = factor * n_max;
console.log("h max is " + h_max);
console.log("n max is " + n_max);
//var h_max = Math.max(h);
//var a = parseInt(nums);
//var create = document.getElementById("shape");
for (var i = 0; i <= nums.length; i++) {
//var x = parseInt(nums[i]);
//var final_width = w / x;
var x_cor = (i + 1) * w;
//var y_cor = i * w * 0.5;
var h = factor * nums[i];
console.log(x_cor);
console.log(h);
//console.log(h_max);
var change = document.getElementById("histContainer");
//change.className = 'myClass';
var bar = document.createElement("div");
bar.className = 'myClass';
//var c_change = document.createElement("div2");
//change.appendChild(c_change);
change.appendChild(bar);
console.log(change);
//change.style.x.value = x_cor;
//change.style.y.value = y_cor;
bar.style.position = "absolute";
bar.style.top = (h_max - h) + "px";
//bar.style.transform = "rotate(-1deg)"
bar.style.left = i * w * 1 + "px";
bar.style.backgroundColor = "rgb(1,211,97)";
bar.style.opacity = "0.6";
bar.style.width = w + "px";
bar.style.height = h + "px";
//var color1 = document.getElementById("histContainer");
//var bar_color = document.createElement("div");
//color1.appendChild(change);
//bar.style.color = "rgba(1,211,97,0.6)";
}
}
function color() {
//draw();
var change1 = document.getElementsByClassName('myClass');
for (var i = 0; i < change1.length; i++) {
change1[i].style.backgroundColor = "rgb(255,0,27)";
console.log("Change1 = " + change1[i]);
}
// var bar1 = document.createElement("div2");
// change1.appendChild(bar1);
// console.log(change1);
//change1.style.backgroundColor = "rgb(1,,254,16)";
}
$(document).ready(function() {
$(document).on("mouseover", ".myClass", function() {
//var number = this.nums;
//$(this.nums).text($(this.nums).index());
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout", ".myClass", function() {
$(this).css("opacity", shade);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Number:<input type="text" id="number" /><br>
<input type="button" id="button1" value="Draw" onClick="draw()" /><br>
<input type="button" id="button2" value="Change Color" onClick="color()" /><br>
<div id="histContainer" style="position: relative;"> </div>
<!-- <label for="mouseover" id="label1">Bar Value</label><br>
<input type="text" name="mouseover" id="text2" value="0"/><br> -->
<!-- <input type="button" id="color_change" style="float: right;" value="Change Color" /> -->
My Question is- I have entered some numbers as Input, and corresponding histogram is made according to the input values. Now, I have created mouseover() on each bar, and WANT to display their proportionate sizes, as given in input.
Can you provide me some help? Only thing which i figured out was- I have to call my draw function in the jQuery mouseover.
REFER TO the draw() and jQuery function(last)
I have figured out the answer. It is required that the nums array has to be re-declared again.
Solution Achieved
$(document).ready(function() {
$(document).on("mouseover",".myClass", function(){
//var numbers = $("#number").serialize();
//var number = this.nums;
var nums = document.getElementById("number").value.split(",");
$(this).text(nums[$(this).index()]);
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout",".myClass", function() {
$(this).css("opacity", shade);
});
});
});

Javascript mathematics with decimal calculation

I have a weird problem with javascript mathematics here is my code :
<script>
function four() {
var price = document.getElementById("price").value;
var sood = (price * 2.5) / 100;
var pricetopay = price + sood ;
var pishpardakht = pricetopay / 3;
document.getElementById("PISH").value = pishpardakht;
var mabaghi = pricetopay - pishpardakht;
var ghest = mabaghi / 4;
document.getElementById("GHEST").value = ghest;
}
</script>
and when the price is 100 ( price = 100 )
pish : 334.1666666666667
ghest : 167.08333333333331
how can i fix that ?
Here's a solution you had to parse the value that you get from your element.
function four() {
var priceUnparsed = document.getElementById("price").value;
var price= parseFloat(priceUnparsed );
var sood = (price * 2.5) / 100;
var pricetopay = price + sood ;
var pishpardakht = pricetopay / 3;
alert(pishpardakht);
document.getElementById("PISH").value = pishpardakht;
var mabaghi = pricetopay - pishpardakht;
var ghest = mabaghi / 4;
document.getElementById("GHEST").value = ghest;
}
<input id="price" value="100">
<button onclick="four()">Go</button>

Why won't .trim() work with me?

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

Categories