How to display result of addition in input - javascript

I am trying to make a simple calculator, that adds 2 numbers together with the press of a button. I have got the HTML part done, but I have no clue how to make the button add the numbers. I have tried using the event listener, but I was probably missing something. If you could, please write the script, while explaining the most important lines of code. Thank you!
<html>
<head>
<title>A calculator... I guess?</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="main">
<div class="container" style="margin: 100px 200px 0 200px">
<!-- Inputs -->
<p>1st number</p>
<input type="number" id="one">
<p>2nd number</p>
<input type="number" id="two>">
<!-- Button -->
<br>
<br>
<button id="add">Calculate</button>
<!-- Result -->
<p>Result</p>
<input type="text" id="result">
</div>
</div>
<script>
</script>
</body>
</html>

<html>
<head>
<title>A calculator... I guess?</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="main">
<div class="container" style="margin: 100px 200px 0 200px">
<!-- Inputs -->
<p>1st number</p>
<input type="number" id="one">
<p>2nd number</p>
<input type="number" id="two">
<!-- Button -->
<br>
<br>
<button id="add" onClick={calculate()}>Calculate</button>
<!-- Result -->
<p>Result</p>
<input type="text" id="result">
</div>
</div>
<script>
var elementOne =document.getElementById('one');
var elementTwo =document.getElementById('two');
function calculate(){
one = parseInt(elementOne.value)
two = parseInt(elementTwo.value)
document.getElementById('result').value = one + two;
}
</script>
</body>
</html>

The script is very easy, are u new to JS? The script is here below with explanation as you asked for -
//create the function which will run on button click
function calculate() {
var firstNumber = document.getElementById("one").value; //Get the value of the first input and store it in firstNumber variable
var secondNumber = document.getElementById("two>").value; //Get the second one's now
firstNumber = parseInt(firstNumber); //Convert both variables from string to integer for we get variables if string datatype when getting the value from an input
secondNumber = parseInt(secondNumber);
var result = firstNumber + secondNumber; //Add the 2 numbers and store the result in a variable
document.getElementById("result").value=result; //Print the "result" variable in the input you want it to get printed in
}
<html>
<head>
<title>A calculator... I guess?</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="main">
<div class="container" style="margin: 100px 200px 0 200px">
<!-- Inputs -->
<p>1st number</p>
<input type="number" id="one">
<p>2nd number</p>
<input type="number" id="two>">
<!-- Button -->
<br>
<br>
<button id="add" onclick="calculate()">Calculate</button> <!--Onclick attribute determines the function to run on click of the element the attribute is in-->
<!-- Result -->
<p>Result</p>
<input type="text" id="result">
</div>
</div>
<script>
</script>
</body>
</html>

I adapted your html to contain a form. Forms are used for user interaction like entering numbers.
<html lang="en">
<head>
<title>A calculator... I guess?</title>
<script src="AddScript.js" rel="script"></script>
</head>
<body>
<div class="main">
<div class="container" style="margin: 100px 200px 0 200px">
<form >
<!-- Inputs -->
<label for="one">1st number</label><br>
<input type="number" id="one" >
<br>
<label for="two">2nd number</label> <br>
<input type="number" id="two">
<!-- Button --><br>
<br>
<button id="add">Calculate</button>
<br>
<br>
<!-- Result -->
<label for="result">Result</label><br>
<input type="text" id="result">
</form>
</div>
</div>
</body>
</html>
and the javascript. You need to use Number() to convert the text to integers
window.onload = init
function init(){
const button = document.getElementById("add")
button.addEventListener("click", addTwoNumbers)
}
function addTwoNumbers(e){
e.preventDefault()
const one = document.getElementById("one")
const two = document.getElementById("two")
const totalSum = Number(one.value) + Number(two.value)
const result = document.getElementById("result")
result.value = totalSum
}

Related

I want to get the total sum of 3 items based on their price and quantity

I want to get the total sum to display at the bottom of my document of 3 items based on their price and quantity. For example item 1 is worth $5, item 2 is worth $7 and item 3 is worth $11. I need a function and editing on my html input tags so I can display the full total if I where to choose different quantities per item.
This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css">
<script src="app.js"></script>
</head>
<body>
<h1>Marios Pest Control</h1>
<form>
<ul class="myList">
<img src="Blue_Goomba_SMWU.png" class="imgCenter">
<li>Goombas: 5 Coins (ea.)<l1> <br>
Total Number:
<input id="goombasInp" type="number" name="Total Number Of">
<button>add</button>
<br> <br> <br> <br> <br> <br> <br> <br> <br>
<img src="635-6354796_mkdd-bob-omb-bomba-de-tiempo-virus.png">
<li>Bob-ombs: 7 Coins (ea.)<li>
Total Number:
<input id="bob-ombsInp" type="number" name="Total Number Of">
<button>add</button>
<br> <br> <br> <br> <br> <br> <br> <br> <br>
<img src="1200px-DeepCheepNSLU.png">
<li>Cheep-cheeps: 11 Coins (ea.)</li>
Total Number:
<input id="cheep-cheepsInp" type="number" name="Total Number Of">
<button>add</button>
<br> <br> <br> <br> <br> <br> <br> <br> <br>
</ul>
<p id="myP">Click Submit To Get The Total:</p>
<button id="wrapper" onclick="myFunction()">Add Total</button>
</form>
<footer class="myFooter">
<p>Marios Pest Control</p> 2410 Birch Ave Lubbock, Tx 79404 <p>url: mariospestconrol.com <p>email: someone#example.com.</p>
</footer>
</body>
</html>
you can use this variant of myFunction() to get your thing done:
function myFunction(event) {
event.preventDefault();
let goombas = document.getElementById("goombasInp");
let bobombs = document.getElementById("bob-ombsInp");
let cheeps = document.getElementById("cheep-cheepsInp");
goombas = goombas.value * 5;
bobombs = bobombs.value * 7;
cheeps = cheeps.value * 11;
document.getElementById("myP").innerHTML += goombas+bobombs+cheeps;
}
document.querySelector("button#wrapper").addEventListener('click', myFunction);
I'll recommend/suggest you to remove: onclick="myFunction()", from your button, and move your script tag at the end of the file, right before you close

Send JavaScript variable to HTML page

I have the following HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
I want to get the value that is introduced in value1 and when the submit is clicked to put that value in the output. So I wrote in script.js the following code but somehow it doesn't work.
<script>
window.onload = function(){
var val = document.getElementById('value1').innerHTML;
document.getElementById('result').innerHTML = val;
};
</script>
Any ideas?
You have to use .value property of the input field instead of innerHTML. so it would be:
var val = document.getElementById('value1').value;
and also, since you're executing it when the page loads. There will be no value assigned to the input field with id 'value1'. Therefore, you won't get any result.
You can try adding a button with onClick event to execute this function in place of using window.onload
HTML controls you are working on are textboxes, so they have a value property, not innerHTML.
Use this:
var val = document.getElementById('value1').value;
document.getElementById('result').value= val;
You can't get the value of an input element using the innerHTML attribute. Use value instead:
var val = documento.getElementById('value1').value;
Also you should keep in mind that your function is executed when the page loads, NOT when the form is submitted.
The code is not working, because you are calling this function when the window loads, not when the submit button is clicked. Since there is no form, and thus no page loading going on, I'd recommend switching the <input type="submit" value="Click" /> to a button. They are functionally similar, and visually identical. With the the button, though you could use the onclick attribute to call a function when the button is clicked. See below for an example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>demo</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<button onclick="printOutput()">Click</button>
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
</body>
</html>
Then in your script.js you would have,
function printOutput(){
var val = document.getElementById('value1').value;
document.getElementById('result').innerHTML = val;
}
when the submit is clicked to put that value in the output
You have chosen wrong event window.onload, also you need .value instead of .innerHTML
Option 1: using jQuery, as you already have the import
$(function() {
$('input[type="submit"]').on('click', function(e) {
$('#result').val($('#value1').val());
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
Option 2: using plain js
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
document.querySelector('#result').value = document.querySelector('#value1').value;
});
});
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="field">
<label for="value1">Introduce value</label>
<input type="text" id="value1" name="value1" value="" />
</div>
<div class="button-block">
<input type="submit" value="Click" />
</div>
<div id="output">
<h2>Result:</h2>
<textarea name="result" id="result"></textarea>
</div>
<script>
$( document ).ready(function() {
setTimeout(function(){
var val = document.getElementById('value1').innerHTML;
var generateHere = document.getElementById("result");
generateHere.innerHTML = val;
}, 2000);
});
</script>

Javascript transfer information from one page to another

I am trying to create a page when you input a number and then on a separate page it displays the multiplication of that number up to and including 10. I can get it to display the table on a new page with document.write but with no formatting and still using the same URL as the first. So far I have tried:
window.location.href
location.href
return
Original Page: Assignment2_Input.html
Result Page: Assignment2_Outpul.html
Script: Assignment2Script.js
Any help would be appreciated!
Orginal Page:
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Input</title>
<link href="Assignment2InputStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="container">
<div id="title">
<h2>Assignment 2</h2>
<h1>Multiplication Table</h1>
<form method="post"><label id="NumberLabel">Please Enter Number: </label><input id="Number" type="text" size="25"></form>
<br/>
<input id="submitButton" type="submit" value="Calculate" >
<p></p>
</div>
</div>
<br/>
<br/>
<script src="Assignment2_Script.js" type="text/javascript"></script>
</body>
</html>
Result Page: (This is the format I am going for on this URL)
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Input</title>
<link href="Assignment2InputStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="container">
<div id="title">
<h2>Assignment 2</h2>
<h1>Multiplication Table</h1>
<form method="post"><label id="NumberLabel">Please Enter Number: </label><input id="Number" type="text" size="25"></form>
<br/>
<input id="submitButton" type="submit" value="Calculate" >
<p></p>
</div>
</div>
<br/>
<br/>
<script src="Assignment2_Script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function calculate() {
num = document.getElementById("Number").value;
document.write('<body background-color="aqua">');
document.write('<table border="1" cellspacing="0">');
for(i=1;i<=10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");
}
I now have the code working in Chrome(still does not work in Firefox)
However when it switched to the new page it flashes the table up for a second and then it disappears. Any thoughts?

Can't link java into html/html file not replacing text

I have an html and javascript files
function saved() {
"use strict";
var description;
description = document.getElementById("description").value;
}
function savedd() {
"use strict";
var due_date;
due_date = document.getElementById("due_date").value;
}
function saverd() {
"use strict";
var reminder_date = document.getElementById("reminder_date").value;
}
document.getElementsByClassName("result").innerHTML = "My new text!";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=.5, maximum-scale=1, minimum-scale=1, width=device-width" />
</head>
<body>
<div style="margin:0 auto;text-align:center">
<!-- Div align in the middle -->
<div style="margin-left:auto;margin-right:auto;text-align:center">
<form>
Description:<br>
<input type="text" name="description" onchange="saved()"><br>
<br>
<br>
Due Date:<br>
<input type="date" name="due_date" onchange="savedd()" ><br>
<br>
<br>
Reminder Date: <br>
<input type="text" name="reminder_date" onchange="saverd()"><br>
</form>
</div>
<div class="result"> PlaceHolder</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type='text/javascript' src="editpage.js"></script>
</body>
</html>
I want it to eventually replace the PlaceHolder text with the Description stored data so that I know that that part of the script is working properly so I can call on it later, but now it just sticks to saying PlaceHolder
Change getElementsByClassName("result") to getElementsByClassName("result")[0]. Your original call returns a collection of nodes, you want to set the innerHTML on a specific node.
Here's a fixed version of your snippet:
document.getElementsByClassName("result")[0].innerHTML = "My new text!";
<div style="margin:0 auto;text-align:center">
<!-- Div align in the middle -->
<div style="margin-left:auto;margin-right:auto;text-align:center">
<form>
Description:
<br>
<input type="text" name="description" onchange="saved()">
<br>
<br>
<br>Due Date:
<br>
<input type="date" name="due_date" onchange="savedd()">
<br>
<br>
<br>Reminder Date:
<br>
<input type="text" name="reminder_date" onchange="saverd()">
<br>
</form>
</div>
<div class="result">PlaceHolder</div>
</div>

html How can I get multiple instant results from single calculation

Is it possible to get a dozen results from this single basic calculation? I have two output textboxes in the sample code; how can I get these two fields to work?
<!DOCTYPE html>
<html lang = "en">
<head>
<title> multiple results calculation </title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="style" href="css/main.css" type"text/css"/>
<!-- I need multiple results from single calculation!
<script type="text/javascript">
function sum()
{
var width = document.multiple results.width.value;
var height = document.multiple results.value;
var sum = parseInt(width) * parseInt(height) /144;
document.getElementById('Calculate').value = sum;
document.getElementById("results1").readOnly=true;
document.getElementById("results2").readOnly=true;
var result1= $1.99;
var result2= $2.99;
document.getElementById('Calculate').value = sum * result1;
document.getElementById('Calculate').value = sum * result2;
}
</script>
-->
</head>
<body>
<div>
<H2> Multiple instant results from single calculation</h2>
<p> the goal eventually is to have about a dozen results from this single calculation
</div>
<form name="multiple results">
<label for="width"> Width: </label>
<input type="number" <id="width" maxlength="4" size="10" value=""/>
<label for="height"> Height: </label>
<input type="number" <id="height" maxlength="4" size="10" value=""/>
<input type="button" name="button" value="Calculate" onClick="sum"/>
<div>
<label for="result1"> Result1: $ </label>
<input type="number" id="result1" name="result1"/>
<label for="result2"> Result2: $ </label>
<input type="number" id="result2" name="result2"/>
</div>
</form>
</body>
</html>
I found a solution by removing the first document.getElementById('Calculate').value = sum;, changed the remaining getElementById's and input type's to result and result2 also added the missing value="" to input, not necessary but renaming Id's helped me

Categories