Why won't my variables add up? - javascript

EDIT : I managed to solve the problem. Here's the new code :
<body>
<script type="text/javascript">
function get(){};
function add(){
var ff= Number(document.getElementById("fn").value);
var ll= Number(document.getElementById("ln").value);
var gg= ff + ll
document.getElementById("fn").value = "";
document.getElementById("ln").value = "";
document.getElementById("rslt").value = gg};
</script>
<h1>Calculator</h1>
<article id="a1">
<input id="fn" type="number" placeholder="first number" style="display:inline">
<span id="mark">MARK</span>
<input id="ln" type="number" placeholder="last number" style="display:inline">
<span>=</span>
<input id="rslt" type="number" placeholder="result" style="display:inline">
<button type="button" onclick="add();"> + </button>
<button type="button"> - </button>
<button type="button"> X </button>
<button type="button"> % </button>
</article>
<p id="hint">This is a paragraph.</p>
</body>
PS : Thanks for all the answers and comments.
I don't know why my variables "ff" and "ll" won't add up in this page?
What's the problem? I am attempting to create something of a
calculator and is currently programming the ADD function. But when I
enter numbers in both fields and press ADD it doesn't add correctly. I
tried the same method alone without all the other code and it worked.
Here's all of the page code in case I fail to include the part where
the problem lies:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<article>
<h1>Calculator</h1>
<input id="fn" type="real" placeholder="first number"></input>
<span id="mark"> + </span>
<input id="ln" type="real" placeholder="last number"></input>
<span id="e"> = </span>
<input id="re" type="real" value="0" placeholder="result"></input>
<br /> <br />
<table>
<th><button type=button onclick="add()">add +</button></th>
<th><button type=button onclick="subtract()">subtract -</button></th>
<th><button type=button onclick="devide()">devide %</button></th>
<th><button type=button onclick="multiply()">multiply *</button></th>
<th><button type=button onclick="clea()">clear</button></th>
</article>
<script>
//setting up variables
var cc="+"
//setting up functions
//get function
function get(){
var ff=document.getElementById("fn").value
var ll= document.getElementById("ln").value
}
//add function
function add() {get();cc="+";
if (cc=="+"){
document.getElementById("hint").innerHTML = "ADD";
document.getElementById("re").value =ff+ll;
alert(ff)
}}
//subtract function
function subtract() {get(); cc="-"
if (cc=="-"){document.getElementById("hint").innerHTML = "SUBTRACT"}
}
//devide function
function devide() {get();cc="%"
if (cc=="%"){document.getElementById("hint").innerHTML = "DEVIDE"}
}
//multiply function
function multiply() {get();cc="*"
if (cc=="*"){
document.getElementById("hint").innerHTML = "MULTIPLY"}
}
//clear function
function clea() {
document.getElementById("hint").innerHTML = "CLEAR"
document.getElementById("re").value =""}
</script>
<p id="hint" style="background-color:yellow; display:inline"></p>
</body>
</html>

A couple issues I see here:
1) The variables you create in get() are only accessible within the scope of that function. If you want to see the results within the other functions, you have to declare them first outside of the get function:
//setting up variables
var cc="+";
var ll;
var ff;
//setting up functions
function add() {get();cc="+";
if (cc=="+"){
document.getElementById("hint").innerHTML = "ADD";
document.getElementById("re").value ="";
alert(ff)
}}
2) You're not actually adding or subtracting anywhere that I see in your code. You're simply clearing the value of the re element (document.getElementById("re").value ="";) and then alerting the value placed into the ff element (alert(ff))

You need to be aware that you will get a string, when you use
document.getElementById("fn").value
So, before adding the variables ff and ll make sure to convert them to float (or int). You could do something like
re = parseFloat(ff) + parseFloat(ll);
or
re=ff - (-ll);
In the second example the conversion is done implicitly, since the - operator requires numerical arguments. Using the + operator would simply concatenate the two string values.

Here's a JSFiddle example to fix up your add function.
function add() {
var fn = document.getElementById("fn").value
var ln = document.getElementById("ln").value
document.getElementById("re").value = new Number(fn) + new Number(ln);
}

"real" is not a valid type for <input> element, which is also self-closing </input> is invalid HTML; set type to "number" and use .valueAsNumber to get value of as number instead of a string.
Include missing closing </table> tag at HTML.
ff and ll are local variables in get function. Set the variables as global variables for each function to have access to the values.
You can also set #mark .textContent to the current mathematical operation within the respective function calls.
JavaScript at Question does not actually perform any mathematical calculations.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<article>
<h1>Calculator</h1>
<input id="fn" type="number" placeholder="first number">
<span id="mark"> + </span>
<input id="ln" type="number" placeholder="last number">
<span id="e"> = </span>
<input id="re" type="number" value="0" placeholder="result">
<br /> <br />
<table>
<th><button type=button onclick="add()">add +</button></th>
<th><button type=button onclick="subtract()">subtract -</button></th>
<th><button type=button onclick="devide()">devide /</button></th>
<th><button type=button onclick="multiply()">multiply *</button></th>
<th><button type=button onclick="clear()">clear</button></th>
</table>
</article>
<p id="hint" style="background-color:yellow; display:inline"></p>
<script>
//setting up variables
var cc = "+",
ff, ll;
//setting up functions
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
var mark = document.getElementById("mark");
var re = document.getElementById("re");
var hint = document.getElementById("hint");
function log() {
console.log(re.value);
}
//get function
function get() {
ff = fn.valueAsNumber;
ll = ln.valueAsNumber;
}
//add function
function add() {
get();
cc = "+";
hint.innerHTML = "ADD";
mark.textContent = " " + cc + " ";
// do the math here
re.value = ff + ll;
log();
}
//subtract function
function subtract() {
get();
cc = "-";
hint.innerHTML = "SUBTRACT";
mark.textContent = " " + cc + " ";
re.value = ff - ll;
log();
}
//devide function
function devide() {
get();
cc = "/";
hint.innerHTML = "DEVIDE";
mark.textContent = " " + cc + " ";
re.value = ff / ll;
log();
}
//multiply function
function multiply() {
get();
cc = "*"
hint.innerHTML = "MULTIPLY";
mark.textContent = " " + cc + " ";
re.value = ff * ll;
log();
}
//clear function
function clear() {
hint.innerHTML = "CLEAR"
re.value = fn.value = ln.value = "";
}
</script>
</body>
</html>

you don't need
if (cc=="..."){
...
}
just write it like
function add() {
get();
cc=="..."
document.getElementById("hint").innerHTML = "ADD";
document.getElementById("re").value = ff + ll;
mark.innerHTML = cc;
}
try it
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<article>
<h1>Calculator</h1>
<input id="fn" type="number" placeholder="first number">
<span id="mark"> + </span>
<input id="ln" type="number" placeholder="last number">
<span id="e"> = </span>
<input id="re" type="number" value="0" placeholder="result">
<br /> <br />
<table>
<th><button type=button onclick="add()">add +</button></th>
<th><button type=button onclick="subtract()">subtract -</button></th>
<th><button type=button onclick="devide()">devide /</button></th>
<th><button type=button onclick="multiply()">multiply *</button></th>
<th><button type=button onclick="clea()">clear</button></th>
</table>
</article>
<script>
//setting up variables
var cc = "+", ff, ll;
//setting up functions
var mark = document.getElementById("mark");
//get function
function get() {
ff = parseFloat(document.getElementById("fn").value);
ll = parseFloat(document.getElementById("ln").value);
}
//add function
function add() {
get();
cc = "+";
document.getElementById("hint").innerHTML = "ADD";
document.getElementById("re").value = ff + ll;
mark.innerHTML = cc;
}
//subtract function
function subtract() {
get();
cc = "-";
document.getElementById("hint").innerHTML = "SUBTRACT";
document.getElementById("re").value = ff - ll;
mark.innerHTML = cc;
}
//devide function
function devide() {
get();
cc = "/";
document.getElementById("hint").innerHTML = "DEVIDE";
document.getElementById("re").value = ff / ll;
mark.innerHTML = cc;
}
//multiply function
function multiply() {
get();
cc = "*";
document.getElementById("hint").innerHTML = "MULTIPLY";
document.getElementById("re").value = ff * ll;
mark.innerHTML = cc;
}
//clear function
function clea() {
document.getElementById("hint").innerHTML = "CLEAR"
document.getElementById("re").value = ""
}
</script>
<p id="hint" style="background-color:yellow; display:inline"></p>
</body>
</html>

Related

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>

How to set minimum Increment ++ and Decrement -- value (can't go bellow 1) + how to decrease or increase button added value

I am working on a web store which offers 2 pre-assigned options (buy two for XX and buy 3 for XY). I also added a normal - 0 + system whith which the customer can select a different number of products.
I wrote a little code which works fine for +- or 2,3 alone, but if i wanna decrease a number added by 2,3 buttons, it doesn't go from 3 to 2 but to 0 or -1.
So, i want to be able to select pre-defined option 2 or 3 but i also want it to be editable by +- buttons.
Any suggestions?
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="0"></input>
<button class="plus" onclick="buttonClicDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
i++;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
var i = 0;
function buttonClickDOWN() {
i--;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
</script>
As I already mention in the comment, you have a typo in buttonClicDOWN .......missing k. You directly increment/decrement the value of the element. Please see the modified functions:
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
I'd have this added as a comment, but was not able to for missing rep. So an answer:
In simple terms: you are not updating your global variable i when pressing the 2 or 3 button, so when you in/decrease i and assign it to the value property, you do override the old value.
I would recommend to drop the i (global) variable and just to work with the value property, e.g.
function buttonClickDOWN() {
var elm = document.getElementById('gumb2');
if (elm.value > 0)
elm.value--;
else
elm.value = 0;
}
P.S.: as you are using a text type input, you might also want to consider non-numbers the user might have entered.
Why not simply use input type="number"?
<button class="gumb_shop2" onclick="gumb2.value=2">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="gumb2.value=3">3 for 8,99 €</button>
<input type="number" id="gumb2" value="1" step="1" min="1" />
<input type="button" id="order" value="ORDER NOW" />
Here's a simple example that that meets your specs:
<button onclick="setAbs(event)" data-val="2">2 for 10,99 €</button>
<button onclick="setAbs(event)" data-val="3">3 for 8,99 €</button><br/><br/>
<button onclick="down()">-</button>
<input size="2" id="counter" value="0" />
<button onclick="up()">+</button><br/><br/>
<input type="submit" value="Submit" />
<script>
let counter = document.getElementById("counter");
function setAbs(event){
counter.value = event.target.dataset.val;
}
function up(){
counter.value = parseInt(counter.value) + 1;
}
function down(){
if(counter.value > 0){
counter.value = parseInt(counter.value) - 1;
}
}
</script>
this is the answer i was looking for.
Thank you #Mamun for quick response.
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>

What am I missing in my JavaScript code?

I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>
Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.
i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>

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>

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

Categories

Resources