adding two numbers in javascript - javascript

I am trying to add these two numbers for an hour and can't get the result in the third text field. Please help me achieve this. thank you. also please tell me is there any add() method in javascript?
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style type="text/css">
#cal{
border:3px solid green;
padding: 5px;
width:250px;
text-align: center;
}
</style>
</head>
<body>
<button onclick="add()" id="button">Add</button>
<div id="cal">
<input type="text" value=" " id="num1" size="5">
+
<input type="text" value=" " id="num2" size="5">
=
<input type="text" value=" " id="sum" size="5">
</div>
<script>
function add()
{
var a = document.getElementById("num1").value;
var b = document.getElementById("num2").value;
var ans = a + b ;
document.getElementById("sum").value = ans;
}
</script>
</body>
</html>

The input values are strings not numbers. You have to convert them to numbers with the function parseInt() for integers or parseFloat() if they happen to be decimal numbers :
var a = parseFloat(document.getElementById("num1").value);
var b = parseFloat(document.getElementById("num2").value);
var ans = a + b;
document.getElementById("sum").value = ans;

Check this demo
Use JavaScript Number() Function
function add(){
var a = document.getElementById("num1").value;
var b = document.getElementById("num2").value;
var ans = Number(a) + Number(b) ;
document.getElementById("sum").value = ans;
}

Related

Basic Javascript: Cannot output result on html

I'm trying to learn Javascript by making a simple calculator, but somehow the result of the calculation doesn't show up. I'm wondering what's wrong with my code. I've tried many ways to understand the error, but I still don't know why. The calculation works just fine in the console, it's just the output that seems to have the problem.
Can somebody help me?
function calc(){
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min"){
calculate = a - b;
}else if (op == "div"){
calculate = a / b;
}else if (op == "mul"){
calculate = a * b;
}
console.log(calculate);
document.querySelector("#result").innerHtml = calculate;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/main.js">
</script>
</head>
<body>
<form>
Value 1: <input type="text" name="" value="" id="value1">
Value 2: <input id="value2" type="text" name="" value="">
Operator:
<select id="operator" class="" name="">
<option value="add">Add</option>
<option value="min">Min</option>
<option value="div">Div</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()" name="button">Calculate</button>
</form>
<div id="result">
</div>
</body>
</html>
innerHtml is invalid attribute, you need to use innerHTML instead like:
document.querySelector("#result").innerHTML = calculate;
You should be using textContent instead of innerHtml
function calc(){
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min"){
calculate = a - b;
}else if (op == "div"){
calculate = a / b;
}else if (op == "mul"){
calculate = a * b;
}
console.log(calculate);
document.querySelector("#result").textContent = calculate;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/main.js">
</script>
</head>
<body>
<form>
Value 1: <input type="text" name="" value="" id="value1">
Value 2: <input id="value2" type="text" name="" value="">
Operator:
<select id="operator" class="" name="">
<option value="add">Add</option>
<option value="min">Min</option>
<option value="div">Div</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()" name="button">Calculate</button>
</form>
<div id="result">
</div>
</body>
</html>
An "id" should be unique within a page and should not
be used more than once value1 and value2 in doesn't
recognise by documents.querySelector() so instead of
this use
Var a =
parseInt(document.getElementById("value1").value);
var b =
parseInt(document.getElementById("value2").value);

how to add two numbers and display result in heading in javascript

i need to take two numbers from the user input and add them, then display it in a heading like "the total is () " and other function to display the average of them. i tried this code but when i click on the button nothing happen and no result shows to me. can you please help me figure the error
var count = 0;
function start() {
var i = document.getElementById("computeAvg");
i.addEventListener("click", add, false);
}
function add() {
var a, b, c;
a = Number(document.getElementById("quiz1").value);
b = Number(document.getElementById("quiz2").value);
c = a + b;
document.getElementById("sTotal").value = c;
}
function Avg() {
count = count + 1
var d = document.getElementById("sTotal");
var A = x1 + x2 / count;
var av = document.getElementById("cAvg");
av.innerHTML = A;
document.getElementById("myimg").onclick = Avg() {
document.getElementById("myimg").style.visibility = "visible";
}
}
window.onload = start;
<html>
<head>
<meta charset="utf-8">
<title>Quiz Grade Calculator</title>
</head>
<body>
<h2>Quiz Grade Calculator</h2>
<div style="width:45%;">
<img id="myimg" src="check.png" style="float:right; visibility:hidden;">
<div>QUIZ1 <input type="text" size="2" id="quiz1" value="0" onchange="Add()" /> / 5</div>
<div>QUIZ2 <input type="text" size="2" id="quiz2" value="0" onchange="Add()" /> / 5</div>
</div>
<h3>Student Total: <span id="sTotal">0</span></h3>
<input type="button" id="computeAvg" value="Add Quiz" onclick="Add()"> CLASS AVERAGE <input type="text" size="5" id="cAvg" />
</body>
</html>
Problems that I could find
You used the format .onlick = namedFunction() { ... }, which is incorrect. Replace the function name with the keyword function.
Your HTML calls the function Add() with a capital letter, but the function is defined as add().
You try to change the value of a span element, but only input elements can have values. Instead, you need the innerText property.
Other edits I've made
The function Avg() is never used, so I put it into a javascript comment.
When trying to find errors, it's always good to minimise code, so I've removed tags such as body, html or head which are unnecessary to reproduce the problem.
For the purpose of creating a code snippet, I've separated out HTML and javascript. However, I would recommend doing this on a real website as well.
Working code snippet
var count = 0;
function start() {
var i = document.getElementById("computeAvg");
i.addEventListener("click", add, false);
}
function add() {
var a, b, c;
a = Number(document.getElementById("quiz1").value);
b = Number(document.getElementById("quiz2").value);
c = a + b;
document.getElementById("sTotal").innerText = c;
}
/*function Avg() {
count = count + 1
var d = document.getElementById("sTotal");
var A = x1 + x2 / count;
var av = document.getElementById("cAvg");
av.innerHTML = A;
document.getElementById("myimg").onclick = function() {
document.getElementById("myimg").style.visibility = "visible";
}
}*/
window.onload = start;
<h2>Quiz Grade Calculator</h2>
<div style="width:45%;">
<img id="myimg" src="check.png" style="float:right; visibility:hidden;">
<div>QUIZ1 <input type="text" size="2" id="quiz1" value="0" onchange="add()" /> / 5</div>
<div>QUIZ2 <input type="text" size="2" id="quiz2" value="0" onchange="add()" /> / 5</div>
</div>
<h3>Student Total: <span id="sTotal">0</span></h3>
<input type="button" id="computeAvg" value="Add Quiz" onclick="add()"> CLASS AVERAGE <input type="text" size="5" id="cAvg" />
There are a numbers of mistakes, the mains of are:
in function add you should use document.getElementById("sTotal").innerHTML = c; instead value due to span does not have value.
an Add() and add() different names, while add is defined Add is not.
in document.getElementById("myimg").onclick = Avg() {, you forget about function, that cause syntax error.
var count = 0;
function start() {
var i = document.getElementById("computeAvg");
i.addEventListener("click", add, false);
}
function add() {
var a, b, c;
debugger
a = Number(document.getElementById("quiz1").value);
b = Number(document.getElementById("quiz2").value);
c = a + b;
document.getElementById("sTotal").innerHTML = c;
}
function Avg() {
count = count + 1
var d = document.getElementById("sTotal");
var A = x1 + x2 / count;
var av = document.getElementById("cAvg");
av.innerHTML = A;
document.getElementById("myimg").onclick = function Avg() {
document.getElementById("myimg").style.visibility = "visible";
}
}
window.onload = start;
<h2>Quiz Grade Calculator</h2>
<div style="width:45%;">
<img id="myimg" src="check.png" style="float:right; visibility:hidden;">
<div>QUIZ1 <input type="text" size="2" id="quiz1" value="0" onchange="add()" /> / 5</div>
<div>QUIZ2 <input type="text" size="2" id="quiz2" value="0" onchange="add()" /> / 5</div>
</div>
<h3>Student Total: <span id="sTotal">0</span></h3>
<input type="button" id="computeAvg" value="Add Quiz" onclick="add()"> CLASS AVERAGE <input type="text" size="5" id="cAvg" />
<html>
<head>
<meta charset = "utf-8">
<title>Quiz Grade Calculator</title>
<script type="text/javascript">
var count =0;
function start()
{
//var q1 = document.getElementById("quiz1");
//q1.addEventListener("click",Add,false);
// var q2 = document.getElementById("quiz2");
// q2.addEventListener("click",Add,false);
var i = document.getElementById("computeAvg");
i.addEventListener("click", add, false);
}
function add() {
var a = document.getElementById("quiz1").value;
var b = document.getElementById("quiz2").value;
var c = parseInt(a) + parseInt(b);
document.getElementById("sTotal").innerHTML = c;
Avg();
}
function Avg()
{
// since the number of count is predifine
count = 2;
document.getElementById("cAvg").value = (parseInt(document.getElementById("quiz1").value) + parseInt(document.getElementById("quiz2").value)) / count;
document.getElementById("myimg").onclick = Avg();
document.getElementById("myimg").style.visibility = "visible";
}
window.onload=start;
</script>
</head>
<body>
<h2>Quiz Grade Calculator</h2>
<div style="width:45%;">
<img id="myimg" src="check.png" style="float:right; visibility:hidden;">
<div>QUIZ1 <input type="text" size="2" id="quiz1" value="0" onchange="Add()"/> / 5</div>
<div>QUIZ2 <input type="text" size="2" id="quiz2" value="0" onchange="Add()"/> / 5</div>
</div>
<h3>Student Total: <span id="sTotal">0</span></h3>
<input type = "button" id="computeAvg" value = "Add Quiz" onclick="Add()">
CLASS AVERAGE <input type="text" size="5" id="cAvg"/>
</body>

HTML, how to get always +1 sum

I'm doing a point counter in general and I have no idea how to do it anymore, so I would like to add +1 to the sum on the "=" button and add it only once if someone could help me, I would be grateful
Code: https://pastebin.com/C26VFyev
var result = 0;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + 1);
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>
Use a variable for what you add to the sum. Initialize it to 1 for the first time, than change it to 0 for future uses.
var result = 0;
var addition = 1;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + addition);
if (addition == 1) {
addition = 0;
}
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>

How can I fix this simple mean calculator so it works and how can I make it so it takes as many numbers as I want?

I am making a mean calculator with HTML, JS, and Jquery. I wasn't sure how to retrieve the number of numbers that are entered so I came up with var numberOfNumbers = $('input').attr('class').length but I don't think it works. What is a better way to collect the number of numbers used to find the mean? Is there anything else wrong with my code? Also how can I make it so that I can enter as many numbers as I want and find the average of them? Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Find Average</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="meancalculator.js"></script>
</head>
<body>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
</body>
</html>
$(function () {
$('button').click(calculate)
})
var number1 = $('#number1').val()
var number2 = $('#number2').val()
var number3 = $('#number3').val()
var numberOfNumbers = $('input').attr('class').length
function calculate() {
var result = (number1 + number2 + number3) / numberOfNumbers
}
$('span').html(result)
Replace your following code :
var numberOfNumbers = $('input').attr('class').length
to:
var numberOfNumbers = $('.numbers').length
A couple of things:
You are taking input field values outside of calculate function. By that time numbers may not have entered. Same goes for displaying results. Move these lines inside calculate function.
Use $('input.numbers').length to get count of input elements having class numbers
Read the numeric values with + in prefix as +$('#number1').val()
Here is your modified code:
<!DOCTYPE html>
<html>
<head>
<title>Find Average</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="meancalculator.js"></script>
</head>
<body>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
</body>
</html>
<script>
$(function () {
$('button').click(calculate)
})
function calculate() {
var number1 = +$('#number1').val()
var number2 = +$('#number2').val()
var number3 = +$('#number3').val()
var numberOfNumbers = $('input.numbers').length
var result = (number1 + number2 + number3) / numberOfNumbers
$('span').html(result)
}
</script>
Another way to approach the problem is just to have one input into which the user can add a list of numbers to take the mean of:
$(function () {
$('button').click(calculate)
})
var number1 = $('#number1').val()
var number2 = $('#number2').val()
var number3 = $('#number3').val()
var numberOfNumbers = $('input').attr('class').length
function calculate() {
let numbers = $('#numbers').val().split(/[ ,]+/);
let sum = numbers.reduce((c, v) => c + parseInt(v), 0);
let result = sum / numbers.length;
$('span').html(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Enter a list of numbers separated by space or comma:</p>
<input type="text" id="numbers" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
You can use $('input').each() for get inputs in the page and $(e).val() to get value of each element withing the each()
DEMO
$(function() {
$('button').click(calculate)
})
function calculate() {
let result = 0
$('input').each((i, e) => {
let val = parseInt($(e).val());
if (!isNaN(val)) {
result += val
}
})
$('span').html(result / $('input').length);
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
Best case;
You can use "numbers" class for find it.
var numberOfNumbers = $.find('.numbers').length;
Worst case;
If you think you will use "number" class for something else, you can add an data attribute for numbers such as;
<input type="text" id="number1" class="numbers" data-bla-bla="numbers">
and find specified data attribute;
var numberOfNumbers = 0;
$.each($.find('.numbers'),function(a,b) { if ($(b).attr('data-bla-bla') != undefined && $(b).attr('data-bla-bla') == 'numbers') { numberOfNumbers++; } });
I think what you want is something dynamic like this :)
var count = 1,
total = 0,
mean = 0;
$(document).on('click', '#addNewField', function() {
var containerDiv = document.createElement('div');
containerDiv.className += "inputWrapper";
var inputField = document.createElement('input');
inputField.setAttribute('type', 'number');
inputField.className += 'number';
containerDiv.append(inputField);
var deleteSpan = document.createElement('span');
deleteSpan.className += 'delete';
inputField.after(deleteSpan);
$('#fields').append(containerDiv);
inputField.focus();
count++;
$('#count').text(count);
});
$(document).on('keyup', '.number', function() {
calculate();
});
function calculate() {
total = 0;
mean = 0;
$('.number').each(function() {
total += parseFloat($(this).val());
mean = total / count;
});
$('#total').text(total);
$('#mean').text(mean);
}
$(document).on('click', '.delete', function() {
$(this).parent().remove();
count--;
$('#count').text(count);
calculate();
});
.inputWrapper {
position: relative;
}
.number {
width: 200px;
height: 30px;
line-height: 30px;
font-size: 24px;
padding-left: 30px;
margin: 5px 0;
display: block;
}
table td {
text-align: center;
}
input.number+*:after {
content: "×";
font-size: 32px;
top: 0;
left: 5px;
position: absolute;
}
#addNewField {
height: 30px;
width: 235px;
margin: 10px 0 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="fields">
<div class="inputWrapper">
<input type="number" class="number"><span class='delete'></span>
</div>
</div>
<button id="addNewField">+ Add New Field</button>
<table border="1px" cellPadding="10px">
<tr>
<th>Count</th>
<th>Total</th>
<th>Mean</th>
</tr>
<tr>
<td id="count">1</td>
<td id="total">0</td>
<td id="mean">0</td>
</tr>
</table>

Create an HTML form with one field and button

I'm new in coding , there is a question that someone gave me and I can't find the right answer , this is the question :
Create an HTML form with one field and button.On button click,get the input,and return the sum of the previous value and the current input value.The value is 0 and input is 5->output is 5,then value is 5,input is 6-> output is 11 and etc.
I tried few things nothing even close ,
if someone can give me the answer Ill be much appreciated , thanks.
There you go, but you should try doing it yourself. it's pretty easy to google things like "on button click" etc.
var total = 0;
$('.js_send').click(function(){
total += parseInt($('.number').val());
$('.total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" class="number"/>
<input type="button" value="send" class="js_send"/>
<div class="total">0</div>
Here's a JQuery free version
var oldInput = 0,
newInput,
outPut;
document.querySelector("#showSum").onclick = function() {
newInput = parseInt(document.querySelector("#newInput").value),
outPut = newInput + oldInput,
oldInput = outPut,
document.querySelector("#result").innerHTML = outPut;
};
#result {
width: 275px;
height: 21px;
background: #ffb6c1;
}
<input type="number" value="0" id="newInput">
<button id="showSum">Show Results</button>
<br>
<div id="result"></div>
Here is the solution to your problem. Put all below code into a html file and name it as index.html, then run the html page.
<html>
<head>
<title></title>
</head>
<body>
Output : <label id="output">0</label>
<form method="get" action="index.html">
Your Input: <input type="text" id="TxtNum"/>
<input type="hidden" id="lastvalue" name="lastvalue" />
<input type="submit" onclick="return doSum();" value="Sum" />
</form>
<script>
//- get last value from querystring.
var lastvalue = getParameterByName('lastvalue');
if (lastvalue != null) {
document.getElementById("lastvalue").value = lastvalue;
document.getElementById("output").innerHTML = lastvalue;
}
/*
* - function to calculate sum
*/
function doSum() {
var newvalue = 0;
if(document.getElementById("TxtNum").value != '')
newvalue = document.getElementById("TxtNum").value;
var lastvalue = 0;
if(document.getElementById("lastvalue").value != '')
lastvalue = document.getElementById("lastvalue").value;
document.getElementById("lastvalue").value = parseInt(newvalue) + parseInt(lastvalue);
output = parseInt(newvalue) + parseInt(lastvalue);
}
/*
* - function to get querystring parameter by name
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</body>
</html>
If you are doing it in server side, You could have a static variable and update it on button click. More like
public static int prevValue;
public int buttonclick(.....){
int sum = textboxValue + prevValue;
prevValue = textboxValue;
return sum;
}
here is your solution
<script type="text/javascript">
var sum=0;
function summ()
{
localStorage.setItem("value",document.getElementById("text").value);
var v=localStorage.getItem("value");
sum=sum+parseInt(v);
alert(sum);
}
</script>
<html>
<input id="text">
<button id="submit" onclick="summ()">sum</button>
</html>
It will be pretty easy.
Created CodePen
http://codepen.io/anon/pen/eJLNXK
function getResult(){
var myinputValue=document.getElementById("myinput").value;
var resultDiv=document.getElementById("result");
if(myinputValue && !isNaN(myinputValue)){
resultDiv.innerHTML=parseInt(myinputValue) + (resultDiv.innerHTML ? parseInt(resultDiv.innerHTML) : 0);
}
}
<input type="text" id="myinput">
<button id="btngetresult" onclick="getResult()">GetResult</button>
<p>
Result:
<div id="result"></div>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">
function sum() {
var t1 = parseInt(document.getElementById("t1").value);
var t2 = parseInt(document.getElementById("pre").value);
document.getElementById("result").innerHTML = t1+t2;
document.getElementById("pre").value = t1;
}
</script>
</head>
<body>
<div>
<form method="get" action="">
<input type="text" name="t1" id="t1">
<input type="button" value="get sum" name="but" onclick="sum()">
<input type="hidden" name="pre" id="pre" value="0">
</form>
</div>
<div id="result"></div>
</body>
</html>

Categories

Resources