Alec
Alec

Reputation: 9575

JS output to div tag disappears immediately after appearing

I am making a basic calculator, and I want each result of the user's calculation to be shown in a div History. The problem is, whenever a calculation is done, the result appears underneath history for fractions of a second, before disappearing. The function I am using is below:

function sum() {
        getNumbers();
        var sum = input1 + input2;
        alert(sum);
        document.getElementById("History").innerHTML += sum;
}

And my full html/js code if needed:

   var input1, input2

function getNumbers() {
input1 = Number(document.getElementById("imp1").value);
input2 = Number(document.getElementById("imp2").value);
}

function sum() {
	getNumbers();
	var sum = input1 + input2;
	alert(sum);
	document.getElementById("History").innerHTML += "<br>" + sum;
}

function diff() {
	getNumbers();
	var diff = input1 - input2;
	 alert(diff);
	 document.getElementById("History").innerHTML += "<br>" +  diff;
}

function prod() {
	getNumbers();
	var prod = input1 * input2;
	alert(prod);
	document.getElementById("History").innerHTML += "<br>" +  prod;
}

function quot() {
	getNumbers();
	var quot = input1 / input2;
	alert(quot);
	document.getElementById("History").innerHTML += "<br>" +  quot;
}
 

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Calculator</title>
    <link rel ="stylesheet" href="calculator.css" />
    <script src ="calculator.js"></script>
    
    
    <div id="calc">
    	<form name="calc_input">
    	<input type="text" id="imp1" />
    	<input type="text" id="imp2" />
    	<!-- buttons -->
    	<button onclick="sum()" id="add" value="sum">Add</button>
    	<button onclick="diff()" id="subtract" value="diff">Subtract</button>
    	<button onclick="prod()" id="multiply" value="prod">Multiply</button>
    	<button onclick="quot()" id="divide" value="quot">Divide</button>
    
    	</form>
    </div>
    
    <div id="History">
    <p>
    History:
    
    </p>
    </div>
    </head>
    </html>
 

Upvotes: 1

Views: 953

Answers (1)

Christopher
Christopher

Reputation: 875

It could have to do with buttons having a submit behavior by default. Probably when you click it is submitting your form and reloading the page. Try adding type="button" to each button.

Upvotes: 3

Related Questions