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.
HTML
<form method="get" action="">
<fieldset>
<legend>Find Percentage of a Number</legend>
<ul>
<li>
<label for="base">Base:</label>
<input type="text" id="base" />
</li>
<li>
<label for="percent">Percent:</label>
<input type="text" id="percent" />
</li>
<li>
<p><span id="total">Total?</span></p>
</li>
<li>
<input type="submit" id="submit" value="Caculate?" onclick="mainInit()" />
</li>
</ul>
</fieldset>
<script type="text/javascript" src="mathshop.js"></script>
</form>
JavaScript
function mainInit() {
if(document.getElementById) {
if(document.getElementById("submit").onclick) {
grabValues();
}
}
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;
}