What am i doing wrong with this JavaScript code? - javascript

I am trying to make a javascript program that solves the Pythagorean theorem when you give it inputs . But for some reason its not working. Here is the code: `
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script>
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
function myFunction() {
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
</head>
<body>
<strong>A</strong>
<input type="text" id="a"></input> <br>
<strong>B</strong>
<input type="text" id="b"></input><br>
<button onclick="myFunction()">Enter</button>
</body>
</html>

First you need to move your gathering of the data inside of the function. Otherwise you will never have a value for the inputs.
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script>
function myFunction() {
//moved two lines below so they are inside the function declaration.
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
</head>
<body>
<strong>A</strong>
<input type="text" id="a"></input> <br>
<strong>B</strong>
<input type="text" id="b"></input><br>
<button onclick="myFunction()">Enter</button>
</body>
</html>

Just replace the script section with the following one:
<script>
function myFunction() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
All you had to do is to move the getElementById lines insied the function :)

Related

Display answer of 'Add and Subtract' buttons using javascript

So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>
//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>

JavaScript is displaying an incorrect mathematical answer

I wrote this small script that would calculate a students GPA. I decided to test it midway and it appears as if the code messes up.
<!DOCTYPE html>
<html>
<head>
<title>GPA Calculator</title>
</head>
<body>
<input type="text" id="varA">
<input type="text" id="varB">
<input type="text" id="varC">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB', 'varC')"></input>
<h1 id="testResult"></h1>
<script>
function addNumbers(elem1, elem2, elem3) {
var a = document.getElementById(elem1).value;
if (a == 90){
a = 4
}
var b = document.getElementById(elem2).value;
var c = Number(a) + Number(b);
c = c / 8
document.getElementById("testResult").innerHTML = c;
}
</script>
</body>
</html>
For example if I add 2 and 2 and 12 instead of displaying 2 it displays 1.75 which is weird.
You forget to add the third values so you get wrong results.
If you inputs 2,2,12 result is 0.5, because of (2+2)/8 = 4/8 = 0.5.
For 2,12,2 or 12,2,2 result is 1,75 because of (2+12)/8 = 14/8 = 1,75
This should give you the desired result.
<html>
<head>
<title>GPA Calculator</title>
</head>
<body>
<input type="text" id="varA">
<input type="text" id="varB">
<input type="text" id="varC">
<input type="button" value="Add" onclick="addNumbers('varA', 'varB', 'varC')">
<h1 id="testResult"></h1>
<script>
function addNumbers(elem1, elem2, elem3) {
var a = document.getElementById(elem1).value;
if (a == 90){
a = 4
}
var b = document.getElementById(elem2).value;
var c = document.getElementById(elem3).value;
let sum = Number(a) + Number(b) + Number(c);
let result = sum / 8;
document.getElementById("testResult").innerHTML = result;
}
</script>
</body>
</html>

Cide to know if a triangle is right-angled or not the math works fine but can't seem to get the value from the input

I tried changing the value into an integer with parseInt it still didn't work and whenever I run it it always just says NaN.
I tried changing the variables a1, b1 and c1 to number directly by (writing a1 = 3 for example) and it worked fine then. I'm still a novice and I don't know what to do.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<h1> Find c or know if it's a right-angle triangle?</h1>
<div id="isIt">
<h5>Please enter the lengths of each side.</h5>
//input area where you enter the sides of the triangle
<input id="a" type="number" min="0.1" placeholder="a">
<input id="b" type="number" min="0.1" placeholder="b">
<input id="c" type="number" min="0.1" placeholder="c">
<br>
<button onclick="isIt()">is it a Triangle?</button>
<button onclick="findc()">What is c?</button>
</div>
<p id="answer"></p>
<script>
//where my problem is
var a1 = (document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt( a1*a1 + b1*b1);
//function to know if its a triangle
function isIt() {
if (c1 === m) {
document.getElementById('answer').innerHTML = 'YES!';
}else{
var trueC0 = Math.sqrt((a*a) + (b*b));
var trueC2 = trueC0.toString();
document.getElementById('answer').innerHTML = "NO! c needs to be " + trueC2 + " too be a
right-angle triangle";
}
}
//function to calculate c
function findc() {
var c = Math.sqrt( a*a + b*b);
document.getElementById('answer').innerHTML = c.toString() ;
}
</script>
</body>
</html>
There are some issues with this code. First is that you're declaring var a1 b1 c1 and m outside your isIt function. So those variables are created and initialized only when your code loads and not in every call to isIt. That means that when you call isIt those variables aren't updated with the new values on the inputs and the calculations are made with whatever value they had on page load. Second is that here var trueC0 = Math.sqrt((a*a) + (b*b)) and here var c = Math.sqrt( a*a + b*b); you're using var a and b which doesn't exist. That's the reason why it returns Nan. I believe they should be a1 and b1. Here is the working code:
<script>
//function to know if its a triangle
function isIt() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt(a1 * a1 + b1 * b1);
if (c1 === m) {
document.getElementById('answer').innerHTML = 'YES!';
} else {
var trueC0 = Math.sqrt((a1 * a1) + (b1 * b1));
var trueC2 = trueC0.toString();
document.getElementById('answer').innerHTML = "NO! c needs to be " + trueC2 + " too be a right-angle triangle";
}
}
//function to calculate c
function findc() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt(a1 * a1 + b1 * b1);
var c = Math.sqrt(a1 * a1 + b1 * b1);
document.getElementById('answer').innerHTML = c.toString();
}
</script>
Also note that here if (c1 === m) c1 and m can be floating numbers and Javascript has issues with floating numbers comparison. It is very common that it returns false even when the numbers are equal. There are libraries for doing that.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<h1> Find c or know if it's a right-angle triangle?</h1>
<div id="isIt">
<h5>Please enter the lengths of each side.</h5>
//input area where you enter the sides of the triangle
<input id="a" type="number" min="0.1" placeholder="a">
<input id="b" type="number" min="0.1" placeholder="b">
<input id="c" type="number" min="0.1" placeholder="c">
<br>
<button onclick="isIt()">is it a Triangle?</button>
<button onclick="findc()">What is c?</button>
</div>
<p id="answer"></p>
<script>
//where my problem is
//function to know if its a triangle
function isIt() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c1 = document.getElementById('c').value;
var m = Math.sqrt( a1*a1 + b1*b1);
if (c1 == m) {
document.getElementById('answer').innerHTML = 'YES!';
}else{
document.getElementById('answer').innerHTML = "NO! c needs to be " + m + " too be a right-angle triangle"
}
}
//function to calculate c
function findc() {
var a1 = document.getElementById('a').value;
var b1 = document.getElementById('b').value;
var c = Math.sqrt( a1*a1 + b1*b1);
document.getElementById('answer').innerHTML = c;
}
</script>
</body>
</html>
When the script loads, your a1,b1,c1 and m initialized, but at that time, user haven't entered any value, so all of them are undefined. When function isIt and findC execute, they are using undefined values for calculation. That's why your code doesn't work. Also m is a number, but c1 is string, you will need == to compare them, or you need to cast c1 to number if you want to use === for comparing them.
Hope it helps

Finding Factorial of a number through prompt from the user

I have been struggling with the this output from which hangs my browser. When I run the following code it runs fine.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = 5;
for(var i=1;i< 5;i++){
input = i*input;
}
document.write(input);
</script>
</body>
</html>
But this hangs the browser and I have to stop it finally. I cant't find any bug or error in this code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = prompt("Enter the number to get factorial of: ");
var result = input;
for(var i=1;i < input;i++){
result = i * result;
}
document.write(result);
</script>
</body>
</html>
input = i*input; increases input so i < input is always false. Try smth like
var input = parseInt(prompt("Enter the number to get factorial of: "));
var result = input;
for(var i=1;i < input;i++){
result = i * result;
}
document.write(result);
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function fact(num)
{
var x=parseInt(num);
if(x>0)
x=x* fact(x-1);
alert(x);
}</script>
</head>
<body>
<form name="f1">
Enter the Number :<input type="text" length="8" name="txt1"><br>
<input type="button" value="Find factiorial" onclick="fact(txt1.value)">
</form>
</body>
var y = prompt("type number ");
var x = input;
function fact(x) {
if(x==0) {
return 1;
}
return x * fact(x-1);
}
function run(number) {
alert(fact(parseInt(number, 10)));
}
run(x);

put in multiply or divide in input field to perform either multiply or divide on the other 2 input fields

Hey guys im trying to create a function that takes 3 arguments. The first argument is supposed to be "MULTIPLY" or "DIVIDE" in an input field, then followed by two numbers which are also in separate input fields, that should be either multipled or divided according based on the first argument. I cant figure out exactly how i'm supposed to write this down in code.
this is my code so far;
<!DOCTYPE html>
<html>
<head>
<script src="ovning3-3.js"></script>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1></h1>
<p>
</p>
<input id="first" type="text">
<input id="second" type="text">
<input id="third" type="text">
<input type="button" value="Multiply" onclick="multiply()">
<input type="button" value="Divide" onclick="divide()">
<input type="button" value="Multiply and Divide" onclick="multiplyAndDivide()">
</body>
</html>
and the java script;
function multiply() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x * y) * z
alert(result)
}
function divide() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x / y) / z
alert(result)
}
function multiplyAndDivide() {
multiply();
divide();
}
Any help out there?
You can use only one function
function multiplyOrDivide(todo){
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
if(todo==0){
alert(Number(x*y*z));
}
else{
if(y!=0 || z!=0){
alert(Number(x/y)/z);
}
}
}
In onclick you can pass options as multiplyOrDivide(1)
See if this is what you want
<!DOCTYPE html>
<html>
<head>
<script>
function calculate() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var d = document.getElementById("decision").value;
if (d=="*")
result = x*y;
else if(d=="/")
result = x/y;
alert(result)}
</script>
<title></title>
</head>
<body>
<h1></h1>
<select id="decision">
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select><br>
<input id="first" type="text">
<input id="second" type="text"><br>
<input type="button" value="Calculate" onclick="calculate()">
</body>
</html>
Let me know if you need any further explaination
You can use select menu to choice which operation you want to perform. To use js functionality, you can take a look this:
function calculate() {
var selected_operation = document.getElementById("operation");
var operation = selected_operation.options[selected_operation.selectedIndex].value;
if (operation == 'multiply')
multiply(operation);
else if (operation == 'divide')
divide();
else if (operation == 'mulitiply_division')
multiplyAndDivide();
}
function multiply() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x * y) * z
alert(result);
}
function divide() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x / y) / z
alert(result);
}
function multiplyAndDivide() {
multiply();
divide();
}
To see the whole scenario, please visit DEMO
function mul()
{
var a = document.getElementById("v1").value;
var b = document.getElementById("v2").value;
document.getElementById("ans").innerHTML = "Multiplication is: " + a * b;
}
function div()
{
var a = document.getElementById("v1").value;
var b = document.getElementById("v2").value;
document.getElementById("ans").innerHTML = "Division is: " + a / b;
}
<!DOCTYPE html>
<html>
<head>
</head>
<style>
body{
padding-left: 80px;
}
</style>
<body>
<p id="ans"></p>
<input type="text" placeholder="Value 1" id="v1"><br><br>
<input type="text" placeholder="Value 2" id="v2"><br><br>
<input type="button" onclick="mul()" id="mul" value="Multiplication">
<input type="button" id="div" onclick="div()" value="Division">
</body>
</html>
Explanation:
document.getElementById(id).value: The value property sets or returns the value of the value attribute of a text field.
document.getElementById("result").innerHTM : The innerHTML property sets or returns the HTML content (inner HTML) of an element.

Categories