I've written the following code for a JavaScript calculator, but when I hit equal it says "undefined" in the Input field. I can't figure out what's going on with it...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd">
<html />
<head />
<title />Calculator</title>
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS

var inputString = "";
function updateString(value) {
	inputString += value;
	document.Calculator.Input.value = inputString;
}

//STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>

<body />

<form name="Calculator" action="" />
<input type="text" name="Input" /><br />
<input type="button" name="plus" value=" + " onclick="updateString"('+')" />
<input type="button" name="minus" value=" - " onclick="updateString"('-')" />
<input type="button" name="times" value=" x " onclick="updateString"('*')" />
<input type="button" name="div" value=" / " onclick="updateString"('/')" />
<input type="button" name="mod" value=" mod " onclick="updateString"('%')" /><br />
<input type="button" name="zero" value=" 0 " onclick="updateString"('0')" />
<input type="button" name="one" value=" 1 " onclick="updateString"('1')" />
<input type="button" name="two" value=" 2 " onclick="updateString"('2')" />
<input type="button" name="three" value=" 3 " onclick="updateString"('3')" />
<input type="button" name="four" value=" 4 " onclick="updateString"('4')" /><br />
<input type="button" name="five" value=" 5 " onclick="updateString"('5')" />
<input type="button" name="six" value=" 6 " onclick="updateString"('6')" />
<input type="button" name="seven" value=" 7 " onclick="updateString"('7')" />
<input type="button" name="eight" value=" 8 " onclick="updateString"('8')" />
<input type="button" name="nine" value=" 9 " onclick="updateString"('9')" /><br />
<input type="button" name="point" value=" . " onclick="updateString"('.')" />
<input type="button" name="clear" value=" clear " onclick="document.Calculator.Input.value=''; inputString=''" />
<input type="button" name="calc" value=" = " onclick="document.Calculator.Input.value=eval(inputString); inputString=''" />
</form>

</body>
</html>

Some points:

  • Why are you treating head and body tags as having a empty content model by writing them as <head /> and <body />? It's incorrect.
  • You are having one too many double quotes in your onclick handlers. onclick="updateString"('+')" should be onclick="updateString('+')"
  • Placing alert's all over your code or using debugger like 'Firebug' if you are developing for Firefox is a good way to spot such errors.

I would personally go for something along the lines of the below pasted code and make javascript do all the dirty work and keep the markup free of inline javascript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd">
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
var inputString = '';
function init()
{
    var list = getElementsByClassName('calcBtn')[0].getElementsByTagName('*');
    for(var i = 0, limit = list.length; i < limit; ++i)
    {
        var elem = list[i];
        if(elem.type == 'button')
        {
            var str = elem.value;
            elem.onclick = function(e) {
                e = e || window.event;
                var el = e.srcElement || e.target;
                updateString(el);
            }
        }
    }
}

function getElementsByClassName(findClass)
{
    var result = [];
    var list = document.getElementsByTagName('*');
    for(var i = 0, list = list || [], limit = list.length; i < limit; ++i)
    {
        var e = list[i];
        if(e.className.indexOf(findClass) != -1)
        {
            result.push(e);
        }
    }
    return(result);
}

function updateString(elem)
{
    var value = elem.value.replace(/^\s|\s$/g, '')
    inputString += value;
    elem.form.elements['Input'].value = inputString;
}

function compute(frm)
{
    var element, result;
    try
    {
        element = frm.elements['Input'];
        result = eval(inputString);
        element.value = result || 'Empty Expression';
    }
    catch(e)
    {
        element.value = 'Invalid expression';
    }
    inputString = '';    //reset the string
}

function resetForm()
{
    inputString = '';
}
</script>
</head>

<body onload="init()";>
<form name="Calculator" action="#" onreset = "resetForm();"/>
<input type="text" name="Input" /><br />
<div class="calcBtn">
    <input type="button" name="plus" value=" + " />
    <input type="button" name="minus" value=" - " />
    <input type="button" name="times" value=" * " />
    <input type="button" name="div" value=" / " />
    <input type="button" name="mod" value=" mod " /><br />
    <input type="button" name="zero" value=" 0 " />
    <input type="button" name="one" value=" 1 "  />
    <input type="button" name="two" value=" 2 "  />
    <input type="button" name="three" value=" 3 " />
    <input type="button" name="four" value=" 4 "  /><br />
    <input type="button" name="five" value=" 5 "  />
    <input type="button" name="six" value=" 6 "  />
    <input type="button" name="seven" value=" 7 " />
    <input type="button" name="eight" value=" 8 " />
    <input type="button" name="nine" value=" 9 "  /><br />
    <input type="button" name="point" value=" . "  />
</div>
<input type="reset" name="clear" value=" clear " />
<input type="button" name="calc" value=" = " onclick="compute(this.form);" />
</form>
</body>
</html>

Alright, I fixed the html tags. Don't quite know what I was thinking there. As for the extra set of quotes, I just looked at the book that I'm striving to learn from wrong.

Are there any programs out there that can be used to check for general syntax errors in JavaScript?


-kahaj

You can try out the Javascript focussed IDE called 'Aptana' or an online Javascript verifier called 'JSLint' to avoid silly mistakes and assistance with the general javascript syntax.

I would have had a separate function call for each button, and operated a stack with the function calls.

That would be a lot of work for no real reason assuming that the intent of the OP is to build a working calculator and not learn stack operations.

Thanks SOS. I'll give Aptana a try.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.