I’ve got a very simple form on an HTML page I’ve done which works as follows. There are 2 buttons on the page “calculate” and “reset” The user inputs 3 numbers and when they click “calculate” it add’s the values together and also calculates 1%, 2% and 3% of each number (and add’s those values together too). The output is displayed in a table which looks something like this:
input %
input %
input %
total total
calculate reset
Now my rather annoying problem is that I have replaced the buttons with images and since I’ve done this, once I click ‘calculate’ the values do not stay populated in the form and rather annoyingly in FF the page “refreshes” and skips back to the top too! What am I doing wrong? Here’s the JS:
var sInput,dInput,pInput,inputTotal,sMonthly,dMonthly,pMonthly,sAnnual,dAnnual,pAnnual,monthlyT otal,annualTotal;
function takeInput()
{
sInput=parseFloat(document.forms[0].txt1st.value);
dInput=parseFloat(document.forms[0].txt2nd.value);
pInput=parseFloat(document.forms[0].txt3rd.value);
inputTotal=sInput+dInput+pInput;
document.forms[0].spendtotal.value="£ " + inputTotal;
}
function isNan()
{
if (isNaN(sInput || pInput || dInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
function calculateMonthly()
{
sMonthly=sInput*0.01;
dMonthly=dInput*0.02;
if (pInput >= 300) {
pMonthly=300*0.03;
}
else
{
pMonthly=pInput*0.03;
}
monthlyTotal=sMonthly+dMonthly+pMonthly;
//rounded up numbers to the nearest whole number
//i.e. .5+
document.forms[0].supermarket.value="£ " + Math.round(sMonthly);
document.forms[0].deptstores.value="£ " + Math.round(dMonthly);
document.forms[0].petrol.value="£ " + Math.round(pMonthly);
document.forms[0].monthlytext.value="£ " + Math.round(monthlyTotal);
}
function calculateAnnual()
{
sAnnual=sMonthly*12;
dAnnual=dMonthly*12;
pAnnual=pMonthly*12;
annualTotal=sAnnual+dAnnual+pAnnual;
document.forms[0].supermarketAnnual.value="£ " + Math.round(sAnnual);
document.forms[0].departmentstoreAnnual.value="£ " + Math.round(dAnnual);
document.forms[0].petrolAnnual.value="£ " + Math.round(pAnnual);
document.forms[0].annualresult.value="£ " + Math.round(annualTotal);
}
And here’s the code from the form:
<input type="image" src="calculate-btn.gif" onClick="takeInput();calculateMonthly();calculateAnnual();">
<input type="image" src="reset-btn.gif" />
Weird thing is, if I don’t use images then the form stays populated with the output and the buttons work fine. Please be gentle, I am a total Javascript Noob.
Thanks
I think the image button is acting as a submit button and posting the form to the server. Try this:
The
return falsewill cancel submission of the form.