Results 1 to 2 of 2

Thread: Trying to Grab Values from Form and Calculate Output into Span Tag?

  1. #1
    Join Date
    Aug 2012

    Trying to Grab Values from Form and Calculate Output 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;

  2. #2
    Join Date
    May 2012
    St. Helens, UK



    I took the liberty of altering your code slighty:

    (result here: http://pastebin.com/sbBbsQEf)

    It took me a minute to realise what was going on, but what was causing that behaviour was that you've used a form method; and pressing a form submit button causes the web page to refresh itself. You don't need that with JS; you can just capture the data from the form fields and do your calculation, before returning the result to the desired location.

    I've also combined the grabValues() and findTotal() functions into a single calculate() function as I think it looks tidier that way. But that's just my personal aesthetic choice.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center