How to fix these undefined values? - javascript

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

Related

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>

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

What part of this simple Javascript calculator is wrong?

I've recently wrote this simple javascript calculator but it will not work, got any ideas?
function calculateMe() {
var x = document.getElementById("x");
var y = document.getElementById("y");
var e = x + y;
document.getElementById("a").innerHTML = e;
}
<center><input id="x"></input> +
<input id="y"></input><br><br>
<button onclick="calculateMe()">Submit</button><br><br>
<input id="a"></input>
You need to first get the value from the inputs, then set the value like:
function calculateMe() {
var x = +document.getElementById("x").value;
var y = +document.getElementById("y").value;
var e = x + y;
document.getElementById("a").value = e;
}
<input id="x"></input>+
<input id="y"></input>
<br>
<br>
<button onclick="calculateMe()">Submit</button>
<br>
<br>
<input id="a"></input>
The + in the document.getElementById code turns the strings you get into numbers.
<html>
<head>
<script>
function calculateMe() {
var x = parseInt(document.getElementById("x").value);
if(isNaN(x)){
x = 0;
document.getElementById("x").value=x;
alert("The value in the first text box is not a valid number.");
}
var y = parseInt(document.getElementById("y").value);
if(isNaN(y)){
y = 0;
document.getElementById("y").value=y;
alert("The value in the second text box is not a valid number.");
}
var e = x + y;
document.getElementById("a").value = e;
}
</script>
<title>Webpage</title>
</head>
<body>
<center>
<input id="x" type="text"> +
<input id="y" type="text"><br><br>
<button onclick="calculateMe()">Submit</button><br><br>
<input id="a" type="text" readonly>
</center>
</body>
</html>

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.

How can I load a value using html5 local storage

I want to get my input also as an outup in an form table. I copied the code beneath because I only want to know how to get my output.
I think that I have to change this
<input type="button" value="load" onclick="load_local();"/
so when I click on a button I get the value in a box like a form
<!DOCTYPE HTML>
<html>
<head>
<TITLE>HTML5 local storage tester (testbed)</TITLE>
</head>
<body>
<div id="output_area"
style="position:relative;width:100%;height:200px;overflow:auto;
border: dotted 1px #ff0000;">
</div>
<div>
<input id="local_storage_key" type="text" />
<input id="local_storage_value" type="text" />
</div>
<div>
<input type="button" value="load" onclick="load_local();"/>
<input type="button" value="store" onclick="store_local();"/>
</div>
<script id="this_page_js" type="text/javascript">
/* store some string data to local storage
This is using some text input elements on the page
for input.*/
function store_local(domid_prefix){
var keyinput = document.getElementById('local_storage_key').value;
var valinput = document.getElementById('local_storage_value').value;
try{
if(typeof(window.localStorage) != 'undefined'){
window.localStorage.setItem(keyinput,valinput);
}
else{
throw "window.localStorage, not defined";
}
}
catch(err){
output_str("store_local,error," + err);
}
}
/* load some string data from local storage
This is using some text input elements on the page
for the key name input and value output.*/
function load_local(domid_prefix){
var keyinput = document.getElementById('local_storage_key').value;
var valoutput = document.getElementById('local_storage_value');
try {
if(typeof(window.localStorage) != 'undefined') {
valoutput.value = window.localStorage.getItem(keyinput);
}
else {
throw "window.localStorage, not defined";
}
}
catch(err) {
output_str("store_local,error," + err);
}
}
/* function to print to the debug area */
function output_str(str){
var da = document.getElementById("output_area");
da.innerHTML += str + "<br/>";
da.scrollTop = da.scrollHeight;
}
</script>
</body>
</html>
thanks for answering.
<html>
<head>
<title>Test</title>
</head>
<body>
<input type="text" id="txt1" /><br/>
<input type="text" id="txt2" /><br/>
<input type="text" id="txt3" /><br/>
<input type="text" id="txt4" /><br/>
<input type="text" id="txt5" /><br/>
<input type="text" id="txt6" /><br/>
<input type="text" id="txt7" /><br/>
<input type="text" id="txt8" /><br/>
<input type="button" id="btn" value="Save" onclick="javascript: return save();"/>
<div id="output"></div>
<script type="text/javascript" src="http://underscorejs.org/underscore-min.js"></script>
<script type="text/javascript">
function save()
{
var arr =new Array();
var obj1 = parseInt(document.getElementById("txt1").value);
var obj2 = parseInt(document.getElementById("txt2").value);
var obj3 = parseInt(document.getElementById("txt3").value);
var obj4 = parseInt(document.getElementById("txt4").value);
var obj5 = parseInt(document.getElementById("txt5").value);
var obj6 = parseInt(document.getElementById("txt6").value);
var obj7 = parseInt(document.getElementById("txt7").value);
var obj8 = parseInt(document.getElementById("txt8").value);
arr.push(obj1);
arr.push(obj2);
arr.push(obj3);
arr.push(obj4);
arr.push(obj5);
arr.push(obj6);
arr.push(obj7);
arr.push(obj8);
var arrOrdered = _.sortBy(arr, function (item) {
return item; //you could implement your logic in here
});
var html = "";
_.each(arrOrdered, function(item){ html += item + "<br/>";});
document.getElementById('output').innerHTML = html;
}
</script>
</body>
</html>
function load()
{
var arr =new Array();
var obj1 = document.getElementById("txt1").value;
var obj2 = document.getElementById("txt2").value;
var obj3 = document.getElementById("txt3").value;
var obj4 = document.getElementById("txt4").value;
var obj5 = document.getElementById("txt5").value;
var obj6 = document.getElementById("txt6").value;
var obj7 = document.getElementById("txt7").value;
var obj8 = document.getElementById("txt8").value;
arr.push(obj1);
arr.push(obj2);
arr.push(obj3);
arr.push(obj4);
arr.push(obj5);
arr.push(obj6);
arr.push(obj7);
arr.push(obj8);
var arrOrdered = _.sortBy(arr, function (item) {
return item; //you could implement your logic in here
});
iterate.over(arrOrdered);
}

Categories