Cant add input and display the sum in JavaScript - javascript

To learn and study JavaScript, im trying to do a calculator, and as start i tried to do a sum operation by taking 2 input. But somehow there is a problem that i cant see. Can you help me?
Here is the code:
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" name="n1" /><br>
Number 2: <input type="text" name="n2" /><br>
</form>
<button id="b" onclick="func();" />Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum() {
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>

Replace:
function sum() {
With:
function func() {
This prevents you from assigning 2 different types / values to the same variable name.
(You've got an sum function and a sum variable in your question.)
Replace:
document.write(sum);
With
document.getElementById('b').innerHTML = sum;
This snippet adds the result of sum to <p id="b"></p> (So, the result may be: <p id="b">18</p>, for example), instead of arbitrarily adding it to the end of your HTML.
And finally, replace:
Number 1: <input type="text" name="n1"/><br>
Number 2: <input type="text" name="n2"/><br>
With:
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
document.getElementById looks for the id attribute in your HTML, not for the name.

There are two problems:-
Change onclick="func();" to onclick="sum();" , you are calling the wrong/undefined function.
<button id="b" onclick="sum();"/>Sum</button>
Assign input tags id as n1 and n2, you have assigned them as name and are referring to them based on id getElementById()
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>

<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" id="n1" name="n1"/><br>
Number 2: <input type="text" id="n2" name="n2"/><br>
</form>
<button id="b" onclick="sum();"/>Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum()
{
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>

Related

JS Calculator Gives `getElementById is not defined` [duplicate]

This question already has an answer here:
Why am I getting "ReferenceError: getElementById is not defined"?
(1 answer)
Closed 1 year ago.
what's the problem in this code? I have tried and can't figure it out. I am a total newbie in HTML, JavaScript, and CSS.
I am wandering around the internet but I think I am missing something and its a small mistake. can you kindly help? I have to learn this for my upcoming projects
here is the code
function result() {
let a = getElementById("constant").value;
let b = getElementById("height").value;
let c = getElementById("freq").value;
let sum = Number(a) + Number(b) + Number(c);
document.getElementById("Calculate").value = sum;
}
<form>
Di-Electric Constant: <input class="text" Placeholder="Enter Value" id="constant" </input>
<br> Di-Electric Height: <input class="text" Placeholder="Enter Value" id="height" </input>
<br> Operational Frequency: <input class="text" Placeholder="Enter Value" id="freq" </input>
<br>
<br>
<input type="text" id="Calculate" </input>
<input type="button" value="Calculate" onclick="result()">
</form>
<br/>
It is document.getElementById(). See: MDN WebDocs: document.getElementById().
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
function result()
{
let a = document.getElementById("constant").value;
let b = document.getElementById("height").value;
let c = document.getElementById("freq").value;
let sum = Number(a) + Number(b) + Number(c);
document.getElementById("Calculate").value = sum;
}
<!DOCTYPE html>
<html>
<head>
<h1>Microstrip Calculator</h1>
<p>Enter the following values in numeric form:</p>
</head>
<body>
<form>
Di-Electric Constant: <input class="text"Placeholder="Enter Value" id="constant"</input>
<br>
Di-Electric Height: <input class="text"Placeholder="Enter Value" id="height"</input>
<br>
Operational Frequency: <input class="text"Placeholder="Enter Value" id="freq"</input>
<br>
<br>
<input type="text"id="Calculate"</input>
<input type="button" value="Calculate" onclick="result()">
</form>
<br/>
</body>
</html>

JavaScript Form validation using isNaN or Type is not working

I tried to validate user input whether user input is a number or string by using isNaN or Type but it is not working. I wrote the if statement inside my function to validate user inputs. I want to user to prompt a number only, not a string. If user input is a string, I would like to pop up an alert to the user.
Can anyone can spot any mistake on my code? Either I put the code incorrectly or I missed something.
function updateTotal(){
var total = 0;
var list = document.getElementsByClassName('input');
var values = [];
for (var i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
total = values.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
if (isNaN(list)) {
alert("Error on input");
}
avgMarks = total / 5;
document.getElementById("total").value = total;
document.getElementById("display").value = avgMarks;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
</head>
<body>
<h1>Get marks</h1>
<div>
<form id="form" method="post">
<label for="marks">Enter your 5 marks: </label><br>
<p>Mark 1</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 2</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 2</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 4</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Mark 5</p>
<input type="text" class='input' value="0" onchange='updateTotal();'><br>
<p>Total 5 marks : </p>
<input type="text" name="totalMarks" id="total" value=""><br>
<p>The average of your marks is : </p>
<input type="text" name="avgMarks" id="display" value="">
<br>
</form>
</div>
<!--JavaScript-->
<script src="debug1_with_error.js"></script>
</body>
</html>
The variable list is a NodeList of elements, not what you want to test. The values you want to test are each individual value, one at a time, in your values array, or just isNaN(total), because NaN would come through in the total if any one value were NaN.

Using javascript functions in HTML

I am creating a small webpage that will add two input fields together and place the result in another input field. This is what I have:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function add(){
var num1 = parseInt(document.calc.num1.value);
var num2 = parseInt(document.calc.num2.value);
var answer = (num1+num2);
document.getElementById('res').value = answer;
}
</script>
</HEAD>
<BODY>
<FORM NAME="calc">
<INPUT TYPE ="button" NAME="add" Value="+" onClick="add()">
<hr/>
<INPUT TYPE ="text" NAME="num1" Value="">
<INPUT TYPE ="text" NAME="num2" Value="">
<hr/>
<INPUT TYPE ="text" ID="res" NAME="result" VALUE="">
</FORM>
</BODY>
</HTML>
And I am getting the following error when I press the + button.
Uncaught TypeError: object is not a function
Try changing the function name from add to addNumbers or something like that.
onclick is the right attribute to handle click
onClick="add()"
Switch this bit to
onclick="add()"
The problem is the name of the function "add()", change the name and you will see that it will works!
HTML
<p>
<label for="field1">Field 1</label>
<input type="number" id="field1"/>
</p>
<p>
<label for="field2">Field 2</label>
<input type="number" id="field2"/>
</p>
<p>
<label for="total">Total</label>
<input readonly type="number" id="total"/>
</p>
<p>
<input type="button" id="calc" value="Calculate"/>
</p>
Javascript
Goes in a script tag in head.
function sumFields(fields) {
var total = 0;
// goes through each field and adds them to the total
for(var i=0,l=fields.length; i<l; i++)
{ total += parseInt(document.getElementById(fields[i]).value); }
document.getElementById('total').value = total;
}
function calc_click() {
// runs when the button is clicked
sumFields(['field1','field2']);
}
// main function
function init() {
// add button functionality
document.getElementById('calc').addEventListener('click',calc_click,false);
}
// fires when the DOM is loaded
document.addEventListener('DOMContentLoaded',init,false);

Get numerical values from input fields and use them to calculate the surface area of a trapezoid

I am new to Javascript and I will be thankful if someone help me understand what I am doing wrong. I am trying to calculate the surface area of a trapezoid by obtaining values from input fields. When I press the "Calculate S" button I get a "Nan" as an answer.
This is the major part of the HTML code:
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(S)">Calculate S</button>
</form>
And this is the script I am using to obtain the values and calculate the surface:
<script type="text/javascript">
var a=parseInt(document.getElementById("a"), 10);
var b=parseInt(document.getElementById("b"), 10);
var h=parseInt(document.getElementById("h"), 10);
var S=parseInt(((a+b)/2)*h, 10);
</script>
Thanks in advance!
You need to get the value out of each input, not just the input, like this:
<script type="text/javascript">
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
var S=((a+b)/2)*h;
</script>
Use .value property on the input elements to get their contents. then call parseInt on that to get a number.
No need to parseInt the result too.
var S = ((a + b) / 2) * h;
Wrap the code in a callable function if you want it executed on button click (what you have now will execute when the code been parsed by your browser).
Example found here: http://jsfiddle.net/bpwEh/
Updated code:
<head>
<!-- ... -->
<script>
function calc(){
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
return ((a+b)/2)*h, 10;
}
</script>
</head>
<body>
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(calc()); return false;">Calculate S</button>
</form>
</body>

HTML display result in text (input) field?

I have a simple HTML form, with 3 input field, when you hit = button, it suppose to add 2 numbers that you typed in the first 2 input fields and display result in 3rd filed. Is it possible to do that? (I need result in a box (or table) or some thing rather than in plain text). I try the following but doesn't work (it does nothing), can somebody help me?
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').innerHTML = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""> +
<INPUT TYPE="text" NAME="number2" VALUE="">
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()">
<INPUT TYPE="text" ID="add" NAME="result" VALUE="">
</FORM>
</BODY>
</HTML>
innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.
For your case you want to set the value of an input element. So you should use the value attribute.
Change innerHTML to value
document.getElementById('add').value = sum;
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
This should work properly.
1. use .value instead of "innerHTML" when setting the 3rd field (input field)
2. Close the input tags
Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use
document.getElementById('sum').innerHTML = sum;
With .value and INPUT tag
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
with innerHTML and DIV
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').innerHTML = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<DIV ID="add"></DIV>
</FORM>
</BODY>
</HTML>

Categories

Resources