I am creating a simple calculator in javascript but how come each time I added numbers it only adds the the first half of the 2nd number? for example
first input: 55
second input: 55
then it will give me an answer of 60.
it only adds the lower half of the 2nd input.
here's my code
var fnum;
var secondNum;
var operation;
function msg(val){
document.getElementById("fnumtext").value += val;
fnum = val;
}
function showOperation(oper){
document.getElementById("fnumtext").value ="";
document.getElementById("operation").value = oper;
operation = oper;
}
function equal(){
secondNum = document.getElementById("fnumtext").value;
alert(secondNum+operation);
if(document.getElementById("operation").value == "+"){
var x = parseInt(fnum)+parseInt(secondNum);
alert(x);
}else if(document.getElementById("operation").value == "-"){
var x = parseInt(fnum)-parseInt(secondNum);
alert(x);
}else if(document.getElementById("operation").value == "*"){
var x = parseInt(fnum)*parseInt(secondNum);
alert(x);
}else if(document.getElementById("operation").value == "/"){
var x = parseInt(fnum)/parseInt(secondNum);
alert(x);
}else{
alert("choose some Operation");
}
}
my HTML
body>
<input id = "fnumtext"type="text" name="firstnum" /><br />
<input id = "operation" type="text" name="secondnum" /><br />
<input type="button" value="1" onclick="msg('1')" />
<input type="button" value="2" onclick="msg('2')" />
<input type="button" value="3" onclick="msg('3')" /></br>
<input type="button" value="4" onclick="msg('4')" />
<input type="button" value="5" onclick="msg('5')" />
<input type="button" value="6" onclick="msg('6')" /><br/>
<input type="button" value="7" onclick="msg('7')" />
<input type="button" value="8" onclick="msg('8')" />
<input type="button" value="9" onclick="msg('9')" /></br>
<input type="button" value="0" onclick="msg('0')" /></br>
<input type="button" value="+" onclick="showOperation('+')" />
<input type="button" value="*" onclick="showOperation('*')" />
<input type="button" value="/" onclick="showOperation('/')" />
<input type="button" value="-" onclick="showOperation('-')" />
<input type="button" value="DO ZEH OPERATION!" onclick="equal()" />
</body>
In msg, you set the value of fnum rather than appending it. Try changing that to +=.
function msg(val){
document.getElementById("fnumtext").value += val;
fnum += val; // changed this line
}
First you need to keep track whether this is a first operand you're entering now or the second one.
Second, you must add current digit's value to the already accumulated values, not override them.
var fnum;
var secondNum;
var operation;
var firstOperand = true;
function msg(val) {
document.getElementById("fnumtext").value += val;
if (firstOperand) {
fnum = document.getElementById("fnumtext").value;
}
}
function showOperation(oper)
{
firstOperand = false;
document.getElementById("fnumtext").value = "";
document.getElementById("operation").value = oper;
operation = oper;
}
function equal() {
secondNum = document.getElementById("fnumtext").value;
alert(secondNum+operation);
if (document.getElementById("operation").value == "+") {
var x = parseInt(fnum) + parseInt(secondNum);
alert(x);
} else if (document.getElementById("operation").value == "-") {
var x = parseInt(fnum) - parseInt(secondNum);
alert(x);
} else if (document.getElementById("operation").value == "*") {
var x = parseInt(fnum) * parseInt(secondNum);
alert(x);
} else if (document.getElementById("operation").value == "/") {
var x = parseInt(fnum) / parseInt(secondNum);
alert(x);
} else {
alert("choose some Operation");
}
firstOperand = true;
document.getElementById("fnumtext").value = "";
}
Related
I'm practicing if statements and I'm trying to make a calculator. I can enter the numbers but clicking on the add, subtract, multiply or divide buttons does not give me any results. I know there are easier ways to do it but it was just for practice. What have I done wrong?
function operar(boton) {
var num1, num2, resultado;
num1 = document.getElementById("num1");
num2 = document.getElementById("num2");
resultado = document.getElementById("resultado");
if (boton.value == '+') {
resultado.value = Number(num1.value) + Number(num2.value);
} else {
if (boton.value == '-') {
resultado.value = Number(num1.value) - Number(num2.value);
} else {
if (boton.value == '*') {
resultado.value = Number(num1.value) * Number(num2.value);
} else {
if (boton.value == '/') {
resultado.value = Number(num1.value) / Number(num2.value);
}
}
}
}
}
<form>
<div>
<label>Número 1</label>
<input id="num1" type="text" />
</div>
<div>
<label>Número 2</label>
<input id="num2" type="text" />
</div>
<input type="button" value="+" onclick="operar(this)" />
<input type="button" value="-" onclick="operar(this)" />
<input type="button" value="*" onclick="operar(this)" />
<input type="button" value="/" onclick="operar(this)" />
<div>
<label>Resultado</label>
<input type="text" id="resultado" />
</div>
</form>
The snippet you gave here, this code is running perfectly. What else do you want to do?
1) I am trying to calculate discount for price with this code but it does not work.
2) I want to clear form when the radio button is changed. Example the size is M and fill number in quantity input only If I change the size, the form will be clear or after amount show me If I change size, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function () {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if(s && q && m) {
if(q >= 1) {
if(s == 'S') {
result = s * q;
} else if(s == 'M') {
result = s * q;
} else if(s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result*5/100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').innerHTML = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
Your calculations are working as expected.
You have one problem in your Code:
document.getElementById('amount').innerHTML = result.toFixed(2); //Here with innerHTML
inputs cannot contain html. They can only contain a value. The property innerHTML is not ideal for input elements. What you are looking for is:
document.getElementById('amount').value = result.toFixed(2);
You must set the value of your amount, not innerHTML.
I have just edited your Snipped. Notice the changes I made on your code. A lot of stuff were unnecessary. Like your multiple if statements checking for 'S', 'M' ... Because at the end they all lead to the same calculation expression.
window.addEventListener("load", () => {
// clear then textboxes on Size change
document.querySelectorAll("input[name=size]").forEach(input=>{
input.addEventListener('change', ()=>{
clearTextBoxes();
});
});
});
var computeTotal = () =>
{
var s = document.querySelector('input[name=size]:checked').value;
var q = document.getElementById('qty').value;
var m = document.querySelector('input[name=member]:checked').value;
var result; //initialize to empty string
if(s && q && m && q >= 1) {
result = s * q;
result -= m === "YES" ? result*5/100 : 0;
}
// Change innerHTML to value
document.getElementById('amount').value = result == undefined ? " " : result.toFixed(2);
}
var clearTextBoxes = () => {
document.getElementById("qty").value = "";
document.getElementById("amount").value = "";
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="number" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate" onclick="computeTotal()">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
You need to clear the input fields when radio button changes. Find the working demo below
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', total)
});
var total = function() {
var s = Number(document.querySelector('input[name=size]:checked').value);
var q = Number(document.getElementById('qty').value);
var m = document.querySelector('input[name=member]:checked').value;
var result;
if (s && q && m) {
if (q >= 1) {
if (s == 'S') {
result = s * q;
} else if (s == 'M') {
result = s * q;
} else if (s == 'L') {
result = s * q;
} else {
result = s * q;
}
result -= m === "YES" ? result * 5 / 100 : 0;
} else {
result = " ";
}
} else {
result = " ";
}
document.getElementById('amount').value = result.toFixed(2);
}
const clearForm = () => {
document.getElementById('myForm').reset();
}
// Add event listener to all radio items and add the clearfields logic
var memberRadios = document.querySelectorAll('input[type=radio][name="member"]');
var sizeRadios = document.querySelectorAll('input[type=radio][name="size"]');
Array.prototype.forEach.call(memberRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
Array.prototype.forEach.call(sizeRadios, function(radio) {
radio.addEventListener('change', clearFields);
});
function clearFields(event) {
document.getElementById('qty').value = null;
document.getElementById('amount').value = null;
}
<form id="myForm">
<p>Member:
<input type="radio" name="member" value="YES">YES
<input type="radio" name="member" value="NO">NO
</p>
<div>
<p>Size:
<input type="radio" name="size" id="S" value="249">S
<input type="radio" name="size" id="M" value="269">M
<input type="radio" name="size" id="L" value="309">L
<input type="radio" name="size" id="XL" value="319">XL
</p>
</div>
<p>Quantity:
<input type="text" name="qty" id="qty">
</p>
<p>Amount: $
<input type="text" name="amount" id="amount" readonly>
</p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Reset</button>
</form>
I'm a complete beginner at this and have started learning javascript through free code camp. I'm trying to write a program to make a calculator using basic javascript. My calculator seems to work fine except for it has a couple of issues that I want to fix. Edit to clarify what I'm asking for help here. Please run my codes in the snippet below with the following operation and you'll understand what I'm asking. Type 9-2 then hit '=' the calculator should display '7'. If you type a '2' immediately after the '7' is displayed, it will give you a '72' on the screen which is what I don't want it to do. I want it to reset to a blank screen. The other issue I have is a repeating display of operators. I've used the codes supplied by other commenters but they don't seem to work. I will keep searching for solution. Thank you all.
the operators: +, -, *, / and . are at this time can be repeated when pushing the button repeatedly. How do I create a function to only allow it to be displayed once.
After hitting the 'equal' button with the result displayed on the screen. If I pressed another number it would add on to the result instead of starting on a new screen. I need for it to reset and start a new using my current codes.
Any guidance and direction is appreciated. I have search Google for days now and still stuck. I'm also terrible at logic which I'm trying my best to wrap my head around this. Thanks.
var show = document.getElementById('display');
var reset = false;
function clear() {
if (reset) {
show.value = '';
reset = false;
}
}
function toScreen(x) {
clear();
show.value += x;
if (x === 'c') {
show.value = '';
}
}
function answer() {
x = show.value;
x = eval(x);
show.value = x;
reset = false;
}
function power() {
x = show.value;
x = eval(x * x);
show.value = x;
}
function backspace() {
var num = show.value;
var len = num.length - 1;
var newNum = num.substring(0, len);
show.value = newNum;
}
function percent() {
x = show.value;
x = eval(x / 100);
show.value = x;
}
function opposite() {
var n = show.value;
n = n * -1;
show.value = n;
}
function sqrt() {
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0)
ans = "Try a positive number!";
show.value = ans;
}
function pie() {
var pi = show.value;
var result = Math.PI;
show.value = result;
}
<form>
<input type="text" id="display" disabled><br>
<input type="button" value="C" id="keys" onclick="toScreen('c')">
<input type="button" value="DEL" id="keys" onclick="backspace()">
<input type="button" value="π" id="keys" onclick="pie()">
<input type="button" value="+/-" id="keys" onclick="opposite()"><br>
<input type="button" value="√" id="keys" onclick="sqrt()">
<input type="button" value="%" id="keys" onclick="percent()">
<input type="button" value="x^2" id="keys" onclick="power()">
<input type="button" value="+" id="keys" onclick="toScreen('+')"><br>
<input type="button" value="9" id="keys" onclick="toScreen('9')">
<input type="button" value="8" id="keys" onclick="toScreen('8')">
<input type="button" value="7" id="keys" onclick="toScreen('7')">
<input type="button" value="-" id="keys" onclick="toScreen('-')"><br>
<input type="button" value="6" id="keys" onclick="toScreen('6')">
<input type="button" value="5" id="keys" onclick="toScreen('5')">
<input type="button" value="4" id="keys" onclick="toScreen('4')">
<input type="button" value="*" id="keys" onclick="toScreen('*')"><br>
<input type="button" value="3" id="keys" onclick="toScreen('3')">
<input type="button" value="2" id="keys" onclick="toScreen('2')">
<input type="button" value="1" id="keys" onclick="toScreen('1')">
<input type="button" value="/" id="keys" onclick="toScreen('/')"><br>
<input type="button" value="0" id="keys" onclick="toScreen('0')">
<input type="button" value="." id="keys" onclick="toScreen('.')">
<input type="button" value="=" id="equal" onclick="answer()"><br>
</form>
See the codes
Here is the perfectly working code. You can replace x with i some places like:
function power() {
x = eval(i * i);
show.value = x;
reset = true;
}
Problem fixed:
Your 1st & 2nd problem
Your code didn't check is input starting from a num. or operator (/1, *1)
Your code didn't check for invalid input (1+, 1+1+ etc)
Your code also not clear screen (like in case of anser) after power Pi etc
Your function like PI Power not check if input is a number (power of 8*) see the power function:
var show = document.getElementById('display');
var reset = false;
var i = ""; //store what is typed
function clear() {
if (reset) {
i = '';
show.value = i;
reset = false;
}
}
function toScreen(x) {
clear();
if (x === "+" || x === "-" || x === "*" || x === "/" || x === ".") {
if (i.charAt(i.length - 1) === x) {
return false;
}
if (i.length === 0) {
return false;
}
}
i += x;
if (x === 'c') {
i = '';
}
show.value = i;
}
function answer() {
var op = ["+", "-", "*", ".", "/"];
for (a=0; a<op.length; a++) {
if (i.charAt(i.length - 1) === op[a]) {
alert("Wrong input");
return false;
}
}
x = show.value;
x = eval(x);
show.value = x;
reset = true;
}
function power() {
if (isNaN(i)) {
alert("please enter a valid number");
return false;
}
x = show.value;
x = eval(x * x);
show.value = x;
reset = true;
}
function backspace() {
var num = show.value;
var len = num.length - 1;
var newNum = num.substring(0, len);
show.value = newNum;
reset = true;
}
function percent() {
x = show.value;
x = eval(x / 100);
show.value = x;
reset = true;
}
function opposite() {
var n = show.value;
n = n * -1;
show.value = n;
reset = true;
}
function sqrt() {
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0)
ans = "Try a positive number!";
show.value = ans;
reset = true;
}
function pie() {
var pi = show.value;
var result = Math.PI;
show.value = result;
reset = true;
}
<form>
<input type="text" id="display" disabled><br>
<input type="button" value="C" id="keys" onclick="toScreen('c')">
<input type="button" value="DEL" id="keys" onclick="backspace()">
<input type="button" value="π" id="keys" onclick="pie()">
<input type="button" value="+/-" id="keys" onclick="opposite()"><br>
<input type="button" value="√" id="keys" onclick="sqrt()">
<input type="button" value="%" id="keys" onclick="percent()">
<input type="button" value="x^2" id="keys" onclick="power()">
<input type="button" value="+" id="keys" onclick="toScreen('+')"><br>
<input type="button" value="9" id="keys" onclick="toScreen('9')">
<input type="button" value="8" id="keys" onclick="toScreen('8')">
<input type="button" value="7" id="keys" onclick="toScreen('7')">
<input type="button" value="-" id="keys" onclick="toScreen('-')"><br>
<input type="button" value="6" id="keys" onclick="toScreen('6')">
<input type="button" value="5" id="keys" onclick="toScreen('5')">
<input type="button" value="4" id="keys" onclick="toScreen('4')">
<input type="button" value="*" id="keys" onclick="toScreen('*')"><br>
<input type="button" value="3" id="keys" onclick="toScreen('3')">
<input type="button" value="2" id="keys" onclick="toScreen('2')">
<input type="button" value="1" id="keys" onclick="toScreen('1')">
<input type="button" value="/" id="keys" onclick="toScreen('/')"><br>
<input type="button" value="0" id="keys" onclick="toScreen('0')">
<input type="button" value="." id="keys" onclick="toScreen('.')">
<input type="button" value="=" id="equal" onclick="answer()"><br>
</form>
function answer() {
x = show.value;
x = eval(x);
show.value = x;
reset = true;
}
Change the reset to true, so that it clears the show.value to be an empty string, that solves nr.2 for you
Edit your toScreen() function to only add your operator if it was
not previously typed:
function toScreen(x) {
clear();
var notTwice = ['+', '-', '*', '/', '.']; //List of chars that should not be repeated
if(notTwice.indexOf(x) > -1){
if(show.value.slice(-1) != x){ //Only type it if it wasn't typed right before
show.value += x;
}
}
else{
show.value += x;
}
if (x === 'c') {
show.value = '';
}
}
Just set reset to false in your answer() function.
Here is a working snippet for you :
var show = document.getElementById('display');
var reset = false;
var i = ""; //store what is typed
function clear() {
if (reset) {
i = '';
show.value = i;
reset = false;
}
}
function toScreen(x) {
clear();
var notTwice = ['+', '-', '*', '/', '.']; //List of chars that should not be repeated
if(notTwice.indexOf(x) > -1){
if(show.value.slice(-1) != x){ //Only type it if it wasn't typed right before
show.value += x;
}
}
else{
show.value += x;
}
if (x === 'c') {
show.value = '';
}
}
function answer() {
var op = ["+", "-", "*", ".", "/"];
for (a=0; a<op.length; a++) {
if (i.charAt(i.length - 1) === op[a]) {
alert("Wrong input");
return false;
}
}
x = show.value;
x = eval(x);
show.value = x;
reset = false;
}
function power() {
if (isNaN(i)) {
alert("please enter a valid number");
return false;
}
x = show.value;
x = eval(x * x);
show.value = x;
reset = true;
}
function backspace() {
var num = show.value;
var len = num.length - 1;
var newNum = num.substring(0, len);
show.value = newNum;
reset = true;
}
function percent() {
x = show.value;
x = eval(x / 100);
show.value = x;
reset = true;
}
function opposite() {
var n = show.value;
n = n * -1;
show.value = n;
reset = true;
}
function sqrt() {
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0)
ans = "Try a positive number!";
show.value = ans;
reset = true;
}
function pie() {
var pi = show.value;
var result = Math.PI;
show.value = result;
reset = true;
}
<form>
<input type="text" id="display" disabled><br>
<input type="button" value="C" id="keys" onclick="toScreen('c')">
<input type="button" value="DEL" id="keys" onclick="backspace()">
<input type="button" value="π" id="keys" onclick="pie()">
<input type="button" value="+/-" id="keys" onclick="opposite()"><br>
<input type="button" value="√" id="keys" onclick="sqrt()">
<input type="button" value="%" id="keys" onclick="percent()">
<input type="button" value="x^2" id="keys" onclick="power()">
<input type="button" value="+" id="keys" onclick="toScreen('+')"><br>
<input type="button" value="9" id="keys" onclick="toScreen('9')">
<input type="button" value="8" id="keys" onclick="toScreen('8')">
<input type="button" value="7" id="keys" onclick="toScreen('7')">
<input type="button" value="-" id="keys" onclick="toScreen('-')"><br>
<input type="button" value="6" id="keys" onclick="toScreen('6')">
<input type="button" value="5" id="keys" onclick="toScreen('5')">
<input type="button" value="4" id="keys" onclick="toScreen('4')">
<input type="button" value="*" id="keys" onclick="toScreen('*')"><br>
<input type="button" value="3" id="keys" onclick="toScreen('3')">
<input type="button" value="2" id="keys" onclick="toScreen('2')">
<input type="button" value="1" id="keys" onclick="toScreen('1')">
<input type="button" value="/" id="keys" onclick="toScreen('/')"><br>
<input type="button" value="0" id="keys" onclick="toScreen('0')">
<input type="button" value="." id="keys" onclick="toScreen('.')">
<input type="button" value="=" id="equal" onclick="answer()"><br>
</form>
i have created a calculator. Now i want to add which can do operation like addition and multiplication.
I'm new to Javascript please anyone can hep me out. I have provided my code here, i'm trying it with event handler. I wanna make it as simple as possible. Please someone help me thanks.
I'm trying this from week please do help with proper examples. Thanks a lot in advance.
if it is possible then please give me an example. Simply i wanna create two functions which can do operations of multiplication and addition using event handlers but not with the two text field my calculator contain one text field so only with one and displays in that same text field.
Refer code:
/*var temp;
function onload() {
temp = document.getElementById('new');
}
function ce(){
var tempo = temp.slice(0, -1);
document.getElementById("new").innerHTML = tempo;
}
*/
/*$(document).ready(function()
{
var temp = $('#new');
var ce = $('#ce');
ce.click(function() {
alert(temp.val());
});
}); */
//var input1=0;
//var input2=0;
// textInputVal= parseInt(document.getElementById('new').value);
function one() {
document.getElementById('new').value += 1;
}
function two() {
document.getElementById('new').value += 2;
}
function three() {
document.getElementById('new').value += 3;
}
function four() {
document.getElementById('new').value += 4;
}
function five() {
document.getElementById('new').value += 5;
}
function six() {
document.getElementById('new').value += 6;
}
function seven() {
document.getElementById('new').value += 7;
}
function eight() {
document.getElementById('new').value += 8;
}
function nine() {
document.getElementById('new').value += 9;
}
function zero() {
document.getElementById('new').value += 0;
}
function actionevent() {
var btn = document.getElementById("plu");
onclick.btn = function() {
textInputVal =
}
}
function ce() {
var textInputVal = 0,
temp = 0;
textInputVal = document.getElementById('new').value;
//console.log(textInputVal);
temp = textInputVal.slice(0, -1);
//console.log(temp);
document.getElementById('new').value = temp;
}
var demo = 0;
function mplus() {
var textInputVal = 0;
textInputVal = parseInt(document.getElementById('new').value);
console.log(textInputVal);
demo += textInputVal;
console.log(demo);
}
var temp = 0;
//var textInputval;
function plus() {
//var textInputval=0;
//var textInputval1=0;
var textInputval = parseInt(document.getElementById('new').value);
console.log(textInputval);
return textInputval;
//document.getElementById("new").value=" ";
//var temp = parseInt(document.getElementById('new').value);
//textInputval1 = parseInt(document.getElementById('new').value);
//temp = textInputval + textInputval1;
//console.log(temp);
//textInputval = $(this).val();
//$(this).val('');
//console.log(textInputval1);
}
function mminus() {
var textInputVal = 0;
textInputVal = parseInt(document.getElementById('new').value);
console.log(textInputVal);
demo -= textInputVal;
console.log(demo);
}
function mr() {
document.getElementById('new').value = demo;
}
/* $(document).ready (function(){
$("#clear_li").click(function(){
$("li:last").remove();
});
}); */
//var inputval=innerHTML - substring;
//var inputval=input.innerHTML;
//var sillyString = inputval.slice(0, -1);
<body>
<div id="cal-container">
<form name="calculator">
<input type="text" name="answer" value="" id="new">
<br>
<input type="button" value=" 1 " onclick="one()" />
<input type="button" value=" 2 " onclick="two()" />
<input type="button" value=" 3 " onclick="three()" />
<input type="button" id="plu" value=" + " onclick="plus()" />
<br>
<input type="button" value=" 4 " onclick="four()" />
<input type="button" value=" 5 " onclick="five()" />
<input type="button" value=" 6 " onclick="six()" />
<input type="button" value=" - " onclick="minus()" />
<br>
<input type="button" value=" 7 " onclick="seven()" />
<input type="button" value=" 8 " onclick="eight()" />
<input type="button" value=" 9 " onclick="nine()" />
<input type="button" value=" * " onclick="multi()" />
<br>
<input type="button" value=" c " onclick="calculator.answer.value = ''" />
<input type="button" value=" 0 " onclick="zero()" />
<input type="button" value=" = " onclick="equal()" />
<input type="button" value=" / " onclick="div()" />
<br>
<input type="button" value="CE" onclick="ce()" />
<input type="button" value="M+" onclick="mplus()" />
<input type="button" value="M-" onclick="mminus()" />
<input type="button" value="mr" onclick="mr()" />
</form>
</div>
</body>
There were few errors in your code I changed them.I have only created for addition,subtraction,multiplication and division.Rest of them you can follow the same way I have done and get the result.
FIDDLE
Here is the code.
var one = function() {
document.getElementById('new').value += 1;
}
var two = function() {
document.getElementById('new').value += 2;
}
var three = function() {
document.getElementById('new').value += 3;
}
var four = function() {
document.getElementById('new').value += 4;
}
var five = function() {
document.getElementById('new').value += 5;
}
var six = function() {
document.getElementById('new').value += 6;
}
var seven = function() {
document.getElementById('new').value += 7;
}
var one = function() {
document.getElementById('new').value += 1;
}
var two = function() {
document.getElementById('new').value += 2;
}
var three = function() {
document.getElementById('new').value += 3;
}
var four = function() {
document.getElementById('new').value += 4;
}
var five = function() {
document.getElementById('new').value += 5;
}
var six = function() {
document.getElementById('new').value += 6;
}
var seven = function() {
document.getElementById('new').value += 7;
}
var eight = function() {
document.getElementById('new').value += 8;
}
var nine = function() {
document.getElementById('new').value += 9;
}
var zero = function() {
document.getElementById('new').value += 0;
}
var plus = function() {
document.getElementById('new').value += "+";
}
var minus = function() {
document.getElementById('new').value += "-";
}
var multi = function() {
document.getElementById('new').value += "*";
}
var div = function() {
document.getElementById('new').value += "/";
}
var equal = function() {
document.getElementById('new').value = eval(document.getElementById('new').value);
}
<body>
<div id="cal-container">
<form name="calculator">
<input type="text" name="answer" value="" id="new">
<br>
<input type="button" value=" 1 " onclick="one()" />
<input type="button" value=" 2 " onclick="two()" />
<input type="button" value=" 3 " onclick="three()" />
<input type="button" id="plu" value=" + " onclick="plus()" />
<br>
<input type="button" value=" 4 " onclick="four()" />
<input type="button" value=" 5 " onclick="five()" />
<input type="button" value=" 6 " onclick="six()" />
<input type="button" value=" - " onclick="minus()" />
<br>
<input type="button" value=" 7 " onclick="seven()" />
<input type="button" value=" 8 " onclick="eight()" />
<input type="button" value=" 9 " onclick="nine()" />
<input type="button" value=" * " onclick="multi()" />
<br>
<input type="button" value=" c " onclick="calculator.answer.value = ''" />
<input type="button" value=" 0 " onclick="zero()" />
<input type="button" value=" = " onclick="equal()" />
<input type="button" value=" / " onclick="div()" />
</form>
</div>
</body>
I am not sure why are you looking for eventListeners however if you want to do by that method then in HTML you have to assign ID to each button and remove onClick event.
<input type="button" value=" 1 id="one" />
And in JavaScript you have to write as follows for each button id
document.getElementById("one").addEventListener("click", one_func);
var one_func= function() {
document.getElementById('new').value += 1;
}
As you see this code is longer then the previous and is not a good practice.So I recommend you to do by the method I have done before.
Hi just out of educational purpose im trying to do a few things with my calculator i did, im trying to get the display to change color depending on result, this is the closest i've come, but it just shows red no matter what the result is, so what more do i need to add?
<script>
function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
kalk.disp.value=("Endast siffror!");
kalk.disp.style.background = "red";
} else {
kalk.disp.value = eval(x);
(eval.value===0)
kalk.disp.style.background = "green";
(eval.value>=1)
kalk.disp.style.background = "blue";
(eval.value<=-1)
kalk.disp.style.background = "red";
}
}
</script>
here's the html
<form name="kalk">
<input type="text" name="disp" >
<br>
<input type="button" value="7" OnClick="kalk.disp.value+='7'">
<input type="button" value="8" OnClick="kalk.disp.value+='8'">
<input type="button" value="9" OnClick="kalk.disp.value+='9'">
<input type="button" value="*" OnClick="kalk.disp.value+='*'">
<br>
<input type="button" value="4" OnClick="kalk.disp.value+='4'">
<input type="button" value="5" OnClick="kalk.disp.value+='5'">
<input type="button" value="6" OnClick="kalk.disp.value+='6'">
<input type="button" value="-" OnClick="kalk.disp.value+='-'">
<br>
<input type="button" value="1" OnClick="kalk.disp.value+='1'">
<input type="button" value="2" OnClick="kalk.disp.value+='2'">
<input type="button" value="3" OnClick="kalk.disp.value+='3'">
<input type="button" value="+" OnClick="kalk.disp.value+='+'">
<br>
<input type="button" value="C" OnClick="kalk.disp.value=''">
<input type="button" value="0" OnClick="kalk.disp.value+='0'">
<input type="button" value="." OnClick="kalk.disp.value+='.'">
<input type="button" value="=" OnClick="checkNum()" >
</form>
its basically this that i have added
(eval.value===0)
kalk.disp.style.background = "green";
(eval.value>=1)
kalk.disp.style.background = "blue";
(eval.value<=-1)
kalk.disp.style.background = "red";
You are using the eval wrong.
You need some if-statements or something like this:
function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
kalk.disp.value = ("Endast siffror!");
kalk.disp.style.background = "red";
} else {
var result = eval(x);
kalk.disp.value = result;
if (result > 0) {
kalk.disp.style.background = "blue";
} else if (result === 0) {
kalk.disp.style.background = "green";
} else {
kalk.disp.style.background = "red";
}
}
}
fiddle
function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
kalk.disp.value = ("Endast siffror!");
kalk.disp.style.background = "red";
} else {
var result = eval(x);
kalk.disp.value = result;
if (result > 0) {
kalk.disp.style.background = "blue";
} else if (result === 0) {
kalk.disp.style.background = "green";
} else {
kalk.disp.style.background = "red";
}
}