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>
Related
I am working on creating a simple increase/decrease percentage calculator using HTML and JavaScript. I honestly am not sure where my actual code is going wrong. It worked fine until I added an if/then statement in the JavaScript. Everything "appears" to be right, but the result is not printing to the screen at the tag ID I specify. I am new to JavaScript and HTML so this is just some learning for me. Thanks in advance!
function getPercentageChange() {
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
if (button1.checked){
var d_oldNumber = document.getElementById('originalnumber').value;
var d_newNumber = document.getElementById('newnumber').value;
var decreaseValue = d_oldNumber - d_newNumber;
var decreaseresults = (decreaseValue / oldNumber) * 100;
document.getElementById('percentageIncrease').innerHTML = descreaseresults + '%';
} else if (button2.checked) {
var i_oldNumber = document.getElementById('originalnumber').value;
var i_newNumber = document.getElementById('newnumber').value;
var increaseValue = i_oldNumber - i_newNumber;
var increaseresults = (increaseValue / i_oldNumber) * 100;
document.getElementById('percentage').innerHTML = increaseresults + '%';
}
}
Percentage Increase <input type="radio" name="radionbutton" value="1" id="button1"/><br>
Percentage Decrease <input type="radio" name="radionbutton" value="2" id="button2"/><br>
<p>Original Number:
<input type="numeric" id="originalnumber" value=""><br>
New Number:
<input type="numeric" id="newnumber" value=""><br><br>
</p>
<input type="button" value="Calculate" onclick="getPercentageChange();">
<div id = "percentage"></div>
<p id="percentage"></p>
This statement uses an undefined variable oldNumber. Perhaps change it to d_oldNumber?
var decreaseresults = (decreaseValue / oldNumber) * 100;
You simply had some miss-spelled variables: d_oldNumber, oldNumber and the id oldNumber.
function getPercentageChange() {
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
if (button1.checked) {
var d_oldNumber = document.getElementById('originalnumber').value;
var d_newNumber = document.getElementById('newnumber').value;
var decreaseValue = d_oldNumber - d_newNumber;
var decreaseresults = (decreaseValue / d_oldNumber) * 100;
document.getElementById('percentage').innerHTML = decreaseresults + '%';
} else if (button2.checked) {
var i_oldNumber = document.getElementById('originalnumber').value;
var i_newNumber = document.getElementById('newnumber').value;
var increaseValue = i_oldNumber - i_newNumber;
var increaseresults = (increaseValue / i_oldNumber) * 100;
document.getElementById('percentage').innerHTML = increaseresults + '%';
}
}
Percentage Increase <input type="radio" name="radionbutton" value="1" id="button1" /><br> Percentage Decrease <input type="radio" name="radionbutton" value="2" id="button2" /><br>
<p>Original Number:
<input type="numeric" id="originalnumber" value=""><br> New Number:
<input type="numeric" id="newnumber" value=""><br><br>
</p>
<input type="button" value="Calculate" onclick="getPercentageChange();">
<div id="percentage"></div>
<p id="percentage"></p>
As a few of your variables equate to the same result, you could simplify this function to save yourself mix-ups. There are a few instances where there were mis-spellings of variable names in your code
function getPercentageChange() {
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var oldNumber = document.getElementById('originalnumber').value;
var newNumber = document.getElementById('newnumber').value;
var difference = oldNumber - newNumber;
var results = (difference / oldNumber) * 100;
if (button1.checked) {
document.getElementById('percentage').innerHTML = results + '%';
} else if (button2.checked) {
document.getElementById('percentage').innerHTML = results + '%';
}
}
Percentage Increase <input type="radio" name="radionbutton" value="1" id="button1" /><br> Percentage Decrease <input type="radio" name="radionbutton" value="2" id="button2" /><br>
<p>Original Number:
<input type="numeric" id="originalnumber" value=""><br> New Number:
<input type="numeric" id="newnumber" value=""><br><br>
</p>
<input type="button" value="Calculate" onclick="getPercentageChange();">
<div id="percentage"></div>
<p id="percentage"></p>
Hope this helps
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>
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>
Updated code. calculate() still not working. The monthly payment amount is ultimately not being passed to the "total" id box. Does anyone see what the underlying problem is here? My syntax seems to be correct, I believe there may be a problem with my specification of where each variable is applied in the code.
I am having problems getting the function calculate() to pass the correct result in "total." Any possible solutions? The action of clicking the calculate button should display the total, but is displaying nothing at all, as if the button does not activate the calculate function at all.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr>
<form name id="Main">
<input type="number" id="price" placeholder="Price of the Car"/>
<br>
<br>
<input type="number" id="DP" placeholder="Down Payment"/>
<br>
<br>
<input type="number" id="R" placeholder="Annual % Rate"/>
<br>
<br>
<input type="number" id="N" placeholder="# of Years Loaned"/>
<br>
<br>
<input type="button" id="calculate" value="Calculate" onclick="javascript:calculate();"/>
<br>
<br>
<input type="number" id="total" placeholder="Total Cost..." readonly=""/>
<br>
<br>
<input type="reset" value="Reset">
</form>
<hr>
</div>
</html>
Use Math.pow() function instead. The ^ operator is not for mathematical power operations (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow).
Also, It's result.value = m, not the other way around :)
Also 2: R and M seem undefined to me, you have to initialize those variables with something, like you did with P and D.
Also 3: use chrome dev tools or anything like that. It will make your life much easier. Remember, javascript doesn't mean "no IDE" :D
Unfortunately, your original code will never work, as it has too many errors.
Here is the corrected fiddle for you, please, have a look:
http://jsfiddle.net/q330fqw8/
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;
}
I removed id="calculate" in HTML, because of this: Why JS function name conflicts with element ID?
In Javascript, the 4 variables P,D,R,N should be set properly. Finally, this m.value = result; -> result.value = m;
but I guess, you've already corrected some errors in the question. I worked with your original code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var P = document.getElementById("price").value;
var D = document.getElementById("DP").value;
var R = document.getElementById("R").value;
var N = document.getElementById("N").value;
var i = (R / 1200);
var n = (N * 12);
var m = ((P - D) * i * Math.pow(1 + i,n)) / (Math.pow(1 + i,n) - 1);
var result = document.getElementById('total');
result.value = m;}
</script>
</head>
<div align="center">
<hr/>
<form id="Main">
<input type="number" id="price" placeholder="Price of the Car" />
<br />
<br/>
<input type="number" id="DP" placeholder="Down Payment" />
<br/>
<br/>
<input type="number" id="R" placeholder="Annual % Rate" />
<br/>
<br/>
<input type="number" id="N" placeholder="# of Years Loaned" />
<br/>
<br/>
<input type="button" value="Calculate Monthly Payment" onclick="calculate();" />
<br/>
<br/>
Total Monthly Payment:<input type="number" id="total" placeholder="Total Cost..." readonly="" />
<br/>
<br/>
<input type="reset" value="Reset" />
</form>
<hr/>
</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/