JavaScript is displaying an incorrect mathematical answer - javascript

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>

Related

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

How to fix these undefined values?

So I have a function that I need to pass 3 values, but my values are allways 0 if I don't enter them, and undefined if enter them. How to fix this issue?
<!DOCTYPE html>
<html>
<head>
<title>Calculate Area</title>
</head>
<body>
<h4>Enter Dimensions</h4>
<input id="a" type="text" name=""><br>
<input id="b" type="text" name=""><br>
<input id="c" type="text" name=""><br>
<input type="button" onclick="calculate()" value="Calculate">
<div id="output"></div>
<script>
var a = Number(document.querySelector('#a').value);
var b = Number(document.querySelector('#b').value);
var c = Number(document.querySelector('#c').value);
function calculate(a, b, c){
//console.log(a);
//console.log(b);
//console.log(c);
return 2*(a*b + a*c + b*c);
}
var p = calculate(a, b, c);
document.querySelector('#output').innerHTML = `<h4>Area = ${p}</h4>`;
</script>
</body>
</html>
You need to get value from elements and set it to #output element each time calculate function is called. Check out my solution below.
var aElement = document.querySelector('#a');
var bElement = document.querySelector('#b');
var cElement = document.querySelector('#c');
var outputElement = document.querySelector('#output');
function updateArea () {
var a = Number(aElement.value);
var b = Number(bElement.value);
var c = Number(cElement.value);
var res = calculate(a, b, c);
outputElement.innerHTML = `<h4>Area = ${res}</h4>`;
}
function calculate (a, b, c) {
return 2*(a*b + a*c + b*c);
}
<h4>Enter Dimensions</h4>
<input id="a" type="text" name=""><br>
<input id="b" type="text" name=""><br>
<input id="c" type="text" name=""><br>
<input type="button" onclick="updateArea()" value="Calculate">
<div id="output"></div>
You are collecting the value of a, b and c at the beginning of the program. At first, the input boxes don't have any value, so the value of a, b and c is undefined. So collect the value when the submit button is clicked.
Try this approach:
function calculate(){
var a = Number(document.querySelector('#a').value);
var b = Number(document.querySelector('#b').value);
var c = Number(document.querySelector('#c').value);
var p = 2*(a*b + a*c + b*c);
document.querySelector('#output').innerHTML = '<h4>Area = ${p}</h4>';
}

Add two numbers and display result in textbox with Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in another text field. But unfortunately the below code is not working. Clicking the button does not show anything in the result text field.
<body>
<div>
<div>
<h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="Text1" name="TextBox1">
<br>
Enter Second Number : <br>
<input type="text" id="Text2" name="TextBox2">
<br>
Result : <br>
<input type="text" id="txtresult" name="TextBox3">
<br>
<input type="button" name="clickbtn" value="Display Result" onclick="add_number()">
<script type="text/javascript">
function add_number(){
var first_number = parseInt(document.getElementsById("Text1").value);
var second_number = parseInt(document.getElementsById("Text2").value);
var result = first_number + second_number;
document.getElementById("txtresult").innerHTML = result;
}
</script>
Here a working fiddle: http://jsfiddle.net/sjh36otu/
function add_number() {
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
var result = first_number + second_number;
document.getElementById("txtresult").value = result;
}
When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
// This is because your method .getElementById has the letter 's': .getElement**s**ById
<script>
function sum()
{
var value1= parseInt(document.getElementById("txtfirst").value);
var value2=parseInt(document.getElementById("txtsecond").value);
var sum=value1+value2;
document.getElementById("result").value=sum;
}
</script>
You made a simple mistake. Don't worry....
Simply use getElementById instead getElementsById
true
var first_number = parseInt(document.getElementById("Text1").value);
False
var first_number = parseInt(document.getElementsById("Text1").value);
Thanks ...
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.minus = function() {
var a = Number($scope.a || 0);
var b = Number($scope.b || 0);
$scope.sum1 = a-b;
// $scope.sum = $scope.sum1+1;
alert($scope.sum1);
}
$scope.add = function() {
var c = Number($scope.c || 0);
var d = Number($scope.d || 0);
$scope.sum2 = c+d;
alert($scope.sum2);
}
});
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h3>Using Double Negation</h3>
<p>First Number:
<input type="text" ng-model="a" />
</p>
<p>Second Number:
<input type="text" ng-model="b" />
</p>
<button id="minus" ng-click="minus()">Minus</button>
<!-- <p>Sum: {{ a - b }}</p> -->
<p>Sum: {{ sum1 }}</p>
<p>First Number:
<input type="number" ng-model="c" />
</p>
<p>Second Number:
<input type="number" ng-model="d" />
</p>
<button id="minus" ng-click="add()">Add</button>
<p>Sum: {{ sum2 }}</p>
</div>
<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>
It should be document.getElementById("txtresult").value= result;
You are setting the value of the textbox to the result. The id="txtresult" is not an HTML element.
<script>
var text1 = document.getElementById("Text1").value;
var text2 = document.getElementById("Text2").value;
var answer = parseInt(text1) + parseInt(text2);
function add_number(){
document.getElementById("txtresult").value = answer;
}
</script>
its Not document.getElementsById function its document.getElementById try it
Instead of writing
.innerHTML = result;
use
.value = result;
<html lang = "en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator DEMO</title>
</head>
<body>
<div>
<p>
<label>Enter Number 1: </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Number 2: </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="resultsum()">+</button>
<button onclick="resultsub()">-</button>
<button onclick="resultmul()">*</button>
</p>
<p>
<button onclick="resultdiv()">/</button>
<button onclick="resultmod()">%</button>
<button onclick="resultper()">percentage</button>
</p>
<script>
function resultsum()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var sm = y + z;
document.getElementById("resultsum").innerHTML = sm;
if(document.getElementById("resultsum").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultsub()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var sb = y - z;
document.getElementById("resultsub").innerHTML = sb;
{
if(document.getElementById("resultsub").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
}
function resultmul()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var ml = y * z;
document.getElementById("resultmul").innerHTML = ml;
if(document.getElementById("resultmul").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultdiv()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var dv = y / z;
document.getElementById("resultdiv").innerHTML = dv;
if(document.getElementById("resultdiv").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultmod()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var md = y + z;
document.getElementById("resultmod").innerHTML = md;
if(document.getElementById("resultmod").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
function resultper()
{
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var per = (y + z )/2;
document.getElementById("resultper").innerHTML = per;
if(document.getElementById("resultper").innerHTML%2!=0)
{
alert('"calculated Result is odd"');
}
else
{
alert('"calculated Result is not "ODD"');
}
}
</script>
<input type="text" name="Answers" id="ans" >
<br/>
<p id="resultsum"></p>
<p id="resultsub"></p>
<p id="resultmul"></p>
<p id="resultdiv"></p>
<p id="resultmod"></p>
<p id="resultper"></p>
</div>
</body>
</html>
You can simply convert the given number using Number primitive type in JavaScript as shown below.
var c = Number(first) + Number(second);

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.

What's wrong in this simple javascript code?

I want to make a program which can sum up all the digits in a given number. I want my script to return the resul on click of the button Please help me find error in my code. Thanks
<!doctype html>
<html>
<head>
<script type="text/javascript">
function sumdigits()
{
var num=document.getElementById("a").value;
var len=num.length();
alert(len);
if(len!=0)
{
var sum=0;
var ldigit=0;
while(num!=0)
{
ldigit=num%10;
sum+=ldigit;
num/=10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number="+sum;
}
</script>
</head>
<body>
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</body>
</html>
DEMO
onClick should be onclick, length() should be length and sum not out of scope
function sumdigits(){
var num = document.getElementById("a").value;
var len = num.length; // note "length"
var sum; // "sum" scope
alert(len);
if(len!==0){
sum = 0;
var ldigit=0;
while(num!==0){
ldigit=num%10;
sum += ldigit;
num /= 10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number = "+ sum;
}
This is how to make it work, now, I don't know what math you're trying to apply in there and what's it's purpose...
The main reason the script is breaking is because you are calling length() on num variable instead of num.length. Below is a link to a working fiddle with that and a few other adjustments made ( check to see if the value's are integers etc...).
http://jsbin.com/uBAyOJep/1/
<!doctype html>
<html>
<head>
</head>
<body>
<form onsubmit="sumdigits()">
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</form>
</body>
</html>
function sumdigits()
{
var sum = 0,
num = document.getElementById("a").value,
len = num.length,
result = document.getElementById("result");
if( len !== 0 ){
for( var i = 0; i < len; i++){
var lineValue = parseInt(num[i], 0);
if ( !isNaN(lineValue) ) {
sum += lineValue;
}
}
}
result.innerHTML="Sum of digits of the given numbers = " + sum;
}

Categories