total numbers printing and calculating with two functions - javascript

I'm total beginner with programming and javascript, i have coded small thing where is two inputs, user writes number on each and program plus it and gives total numbers below it
function printTotal(a,b){
// this function should take values as a parameter
}
function calculateTotal(a,b){
var c=a+b;
// this function should calculate and return
}
document.getElementById("results").innerHTML = "Total= " +printTotal(a,b) ;
<div class="keski">
<form id="f">
<input type=text id="n1"><br>
<input type=text id="n2"><br>
</form>
<button class="g" type="button" onclick="printTotal(f.n1.value, f.n2.value)">Count</button>
<div id="results"></div>
</div>
i have two functions which should help each other in order to make this possible( i have commented the code) , i know how to make this with one function, but dont know how to make it with two functions, do i need to put functions inside each other(nested)? sory english is not my mother language.

In calculateTotal function you need return value. In printTotal you can get value in 2 input and call calculateTotal for calculate total and print it.
Try this code:
function printTotal(a, b){
// this function should take values as a parameter
// print total
document.getElementById("results").innerHTML = "Total= " + calculateTotal(a, b)
}
function calculateTotal(a,b){
// need return total
return Number(a) + Number(b);
// this function should calculate and return
}
<div class="keski">
<form id="f">
<input type=text id="n1"><br>
<input type=text id="n2"><br>
</form>
<button class="g" type="button" onclick="printTotal(f.n1.value, f.n2.value)">Count</button>
<div id="results"></div>
</div>

function printTotal(a,b) {
return calculateTotal(a,b);
}
function calculateTotal(a,b) {
return a+b;
}
Is this what you mean?

You can try with this changes. Basically I moved the code that assigns value to results div, and changed a method call there.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
</style>
</head>
<body>
<div class="keski">
<form id="f">
<input type=text id="n1"><br>
<input type=text id="n2"><br>
</form>
<button class="g" type="button" onclick="printTotal(f.n1.value, f.n2.value)">Count</button>
<div id="results"></div>
</div>
<script>
function printTotal(a,b){
document.getElementById("results").innerHTML = "Total= " +calculateTotal(a,b) ;
}
function calculateTotal(a,b){
var c = Number(a) + Number(b); //I use the 'Number' method here in order to avoid a and b being concatenated (treated like strings)
return c; //This return was missing so we can return value to calling method.
}
</script>
</body>
</html>

Related

Javascript - increment and double a value

I want to write my first code. I made this, but it still needs a change.
There is shown a value and this value can be changed with 2 buttons. When the buttons Increment is pushed, the value has to go with one higher. If the button Double is pressed, then the value has to be double (e.g. going from 3 to 6). Now it is coded like a decrement, but this needs to be changed.
var x = 0
var element = document.getElementById("value");
element.innerHTML = x;
function button1() {
element.innerHTML = ++x;
}
function button2() {
element.innerHTML = --x;
}
<html>
<body>
<title> First code </title>
<body>
<div id="value"></div>
<input type=button value="Increment" onclick="button1()" />
<input type=button value="Double" onclick="button2()" />
</body>
</html>
You need to multiply by 2 rather than subtract 1.
There's no need for the x variable, you can operate directly on the innerHTML. JavaScript's type juggling will automatically convert it to a number when you use these arithmetic operators on it.
var element = document.getElementById("value");
element.innerHTML = '0';
function button1() {
element.innerHTML++;
}
function button2() {
element.innerHTML *= 2;
}
<html>
<body>
<title> First code </title>
<body>
<div id="value"></div>
<input type=button value="Increment" onclick="button1()" />
<input type=button value="Double" onclick="button2()" />
</body>
</html>

Greedy Algorithm

I am writing a piece of code, when a user enters the amount of change owed, returns the minimum amount of coins to equal that change. For instance, assuming only quarters, dimes, nickels and pennies are used. You enter $1.00. The number my code will render on the screen is 4 (4 quarters equaling a dollar). However, I am experiencing a small bug. If you type in $0.41 for example, you'd expect the code to render 4 again (1 quarter + 1 dime + 1 nickel + 1 penny is the minimum amount of permutations to equal 41 cents), but it doesn't, it renders 5.44. Please help! Thank you in advance.
document.write("Hi,how much change is due? ");
function greed () {
var n = document.getElementById('change').value;
if (n >=0)
{
function amount (amt){
return amt/25 + (amt%25)/10 + ((amt%25)%10)/5 + ((amt%25)%10)%5;
}
document.write(amount(Math.round(n*100)));
}
else {alert("Invalid Amount!")};
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Greedy! </title>
<script type="text/javascript" src="greedy.js" ></script>
</head>
<body>
<form>
<fieldset>
<input type="number" id="change" name="change" value="0"/>
<input type="submit" id="submit" name="submit" value="submit" onclick="greed();"/>
</fieldset>
</form>
</body>
</html>
The main problem here is that you're not treating the numbers as integers, so you get decimal numbers everywhere. Let's use your example (0.41):
amt = n*100 = 41, so let's go to the return:
return amt/25 + (amt%25)/10 + ((amt%25)%10)/5 + ((amt%25)%10)%5
which is the same as
return 41/25 + (41%25)/10 + ((41%25)%10)/5 + ((41%25)%10)%5
as you know, 41/25 =/= 1, same with (41%25)/10 = 16/10 =/= 1 and ((41%25)%10)/5 = (16%10)/5 = 6/5 =/= 1, but you don't care about that in the code so you end up adding those decimal numbers till the end, and get weird values.
You must use parseInt() to get Integer values, so it should look like this:
return parseInt(amt/25) + parseInt((amt%25)/10) + parseInt(((amt%25)%10)/5) + ((amt%25)%10)%5
To show it works:
document.write("Hi,how much change is due? ");
function greed () {
var n = document.getElementById('change').value;
if (n >=0)
{
function amount (amt){
return parseInt(amt/25) + parseInt((amt%25)/10) + parseInt(((amt%25)%10)/5) + ((amt%25)%10)%5;
}
document.write(amount(Math.round(n*100)));
}
else {alert("Invalid Amount!")};
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Greedy! </title>
<script type="text/javascript" src="greedy.js" ></script>
</head>
<body>
<form>
<fieldset>
<input type="number" id="change" name="change" value="0"/>
<input type="submit" id="submit" name="submit" value="submit" onclick="greed();"/>
</fieldset>
</form>
</body>
</html>

JavaScript – Problems with Reset button on calculator

I have a simple calculator and I want two text fields to reset when the reset button is clicked, but for some reason it's not working. I've referenced other Stack Overflow inquiries, but some use jQuery. Is there a way to do this without jQuery? Anyways, here's the JSFiddle: http://jsfiddle.net/jsdmLr7b/
<script>
var a, b, result;
function setValues() {
a = Number(document.getElementById('leftInput').value);
b = Number(document.getElementById('rightInput').value);
}
function sum() {
setValues();
result = a + b;
document.getElementById('inputTotal').innerHTML = result;
}
function reset() {
document.getElementByID('inputLeft').innerHTML.value = "";
document.getElementByID('inputRight').innerHTML.value = "";
}
</script>
<div>
<input id="leftInput" type="text" />
<input id="rightInput" type="text" />
<input type="button" onClick="sum()" value="sum" />
<input type="button" onClick="reset()" value="reset" />
<p>Total: <a id="inputTotal"></a>
</p>
</div>
Try this:
<script>
var a, b, result;
function setValues() {
a = Number(document.getElementById('leftInput').value);
b = Number(document.getElementById('rightInput').value);
}
function sum() {
setValues();
result = a + b;
document.getElementById('inputTotal').innerHTML = result;
}
function reset() {
document.getElementById("leftInput").value = "";
document.getElementById("rightInput").value = "";
}
</script>
<div>
<input id="leftInput" type="text" />
<input id="rightInput" type="text" />
<input type="button" onClick="sum()" value="sum" />
<input type="button" onClick="reset()" value="reset" />
<p>Total: <a id="inputTotal"></a>
</p>
</div>
Your problem was that you were calling getElementByID on the document. The proper way to call this is getElementById with a lowercase "d" in "Id."
Also, you were referencing the wrong id values. They are leftInput and rightInput, not inputLeft and inputRight. It can be easy to overlook wording and case sensitivity after looking at code for hours!
I switched the reset function to use .value = ""; because it makes more sense in this case and should be used for input/form operations, while innerHTML is used for other elements (div, span, td, etc.)
You can also clear your total by adding this to the reset() function:
document.getElementById("inputTotal").innerHTML = "";
In this case you want to use innerHTML because your value is not inside an input/form operation. Here's the updated JSFiddle.
I Found A Very Simple Solution Just Wrap Your All Input in FORM Tag and Your Reset button will work Fine

How can i save a value in the textbox to a variable

I want to store the value given in the text box in a variable. I am beginner to javascript. Please help me out. Here s my code.
<!DOCTYPE html>
<html>
<body>
Days of Journey: <input type="text" id="doj" name="daysofjourney">
<input type="button" value="submit" onclick="dayscounter()">
<script language="javascript" type="text/javascript">
var travel = document.getElementById("doj").value;
function dayscounter() {
var days;
for(days = 1; days <= travel; days++) {
document.write(days);
}
}
</script>
</body>
</html>
You nearly had it already...
function dayscounter() {
var travel = document.getElementById("doj").value;
var days;
for(days=1;days<=travel;days++)
{
document.write(days);
}
}
The problem was, that your first assignment of the variable travel is made as soon as the HTML code is loaded. The user can't have made an input yet at that time, thus the variable stays empty. If you include document.getElementById("doj").value inside the function, you will get the value at that specific time you launch the function.
Just parse value to int
var travel = +(document.getElementById("doj").value;);
You can use 'value' attribute of an text input to set it's value like:
<input type="text" id="textid" value="value content" />
and you can do your function like this:
<script language="javascript" type="text/javascript">
function dayscounter()
{
var travel = document.getElementById("doj").value;
var days;
var result = "";
for (days = 1; days <= parseInt(travel); ++days)
{
document.getElementById("result").value += " " + days;
}
}
</script>
Days of Journey:
<input type="text" id="doj" name="daysofjourney" />
<input type="button" value="submit" onclick="dayscounter()" />
<p>
<input type="text" id="result" />
</p>

JavaScript and HTML assignment

Okay, I'm ashamed to be asking, but it just isn't clicking. My brother-in-law has an assignment to have a text box and then a command button. When the button is pressed, it will loop 10 times printing whatever was in the text box. Should be simple - I know!
I know the error is on this line:
<input type="button" value="Press Here" onClick="sayit(document.getElementById('myTextField').value) ">
Here's what we have:
<html>
<head>
<title> Homework #11 part 2 </title>
<script type="text/javascript">
function sayIt(var message){
count = 1;
num = 10;
while (count <= num) {
document.write(message);
document.write("<br/>");
count = count + 1;
}
}
</script>
</head>
<body>
<p>
Type in a phrase.
<input type='text' id='myText' />
<br />
<input type="button" value="Press Here" onClick="sayit(document.getElementById('myTextField').value) ">
</p>
</body>
The code has three thins wrong.
1) function sayIt(var message) should be function sayIt(message)
2)onClick="sayit(....)" should be onClick="sayIt(....)"
sayIt is function name
3)document.getElementById('myTextField').value should be document.getElementById('myText')
myText is input element's id attribute
You've got three things wrong.
http://jsfiddle.net/userdude/jcfD8/
Hints - you don't need var in your function declaration, your id is not right, and you "misspelled" sayIt
( ^ If you care to see the answers, they are above ^ )
Invest in Firebug. It gave me all the answers I needed. ;)

Categories