[help] Why Can't I Calculate and Insert into Span Tag?

This is my first javascript program. I’ve been studying for a few days and thought I’d put it into practice.

The problem is I’m trying to grab 2 numbers and multiply them. This will be a program to calculate percentage of something. I’m testing if two numbers can be multiplied and the output inserted into a span tag with id=“total”. When I hit calculate, it prints the total in span tag but quickly refreshes with default value over the total value.


    	<form method="get" action="">
    			<legend>Find Percentage of a Number</legend>
				    	<label for="base">Base:</label>
				    	<input type="text" id="base" />
						<label for="percent">Percent:</label>
						<input type="text" id="percent" />
						<p><span id="total">Total?</span></p>
						<input type="submit" id="submit" value="Caculate?" onclick="mainInit()" />
		    <script type="text/javascript" src="mathshop.js"></script>


function mainInit() {
	if(document.getElementById) {
		if(document.getElementById("submit").onclick) {
	else {
		alert("Sorry, your browser does not support JavaScript.");

function grabValues() {
	var a = document.getElementById("base").value;
	var b = document.getElementById("percent").value;
	findTotal(a, b);

function findTotal(base, percent) {
	var total = base * percent;
	document.getElementById("total").innerHTML = total;


Hey there,

What’s happening here is that your JavaScript code runs and executes correctly, but as soon as it does the <form> is submitted because you used <input type=“submit”>.

If you want to stop this from happening you can use an <input type=“button”>

I’ll also remark that your mainInit()'s if statement probably doesn’t need to be there. It’s pretty safe to assume that document.getElementById() is available (unless you live in 1994 ;))

It is however a good idea to test for features that are not available in all browsers, for example if your code made use of document.querySelectorAll() it would be a good idea to perform a test and run alternate code.

Thanks. And it didn’t have anything to do with javascript. I was looking over and over in the wrong place.