Cody Mallery
Cody Mallery

Reputation: 131

Creating an Object in JavaScript that does math calculations using values retrieved from a text box?

I'm trying to make a calculator using Objects. Here is JSFiddle: http://jsfiddle.net/jNqEv/4/

I was using this code in order to do the computations of the numbers while I made the rest of the calculator:

/*Computes the values inside the box and returns the answer.*/
function compute(form)  
{
    form.display.value = eval(form.display.value); 
}  

Now I need to create an Object that does the calculations instead of using the JavaScript predefined Object eval. I was thinking something like this:

Basically this Object takes the values from the text box with the id "input" The values would be in the form of 2*3, 1+2,5/7 etc... So I was thinking if I pulled the second piece of data in the string using substr I could then check to see if it was multiply, divide, subtract, or addition.

    function calc(arithmetic)
{
    this.arithmetic = arithmetic;
}        

var myCalc = new calc(input)
    {
    function maths (input) 
{
    var str = input;
    var a=str.substr(1,1); // example: 1+2   var a holds the 1
    var b=str.substr(2,1); //                var b holds the "+"
    var c=str.substr(3,1); //                var c holds the 2
                           // if the sign is equal to "+" add var a plus var b
                           // and then place them inside answerNumber.
                           // then take answerNumber and place its value
                           // inside the page element with the id "input"
    if(b == "+")
    {
        answerNumber = a + c;
    }
    else if(b == "-")
    {
        answerNumber = a + c;
    }
    else if(b == "*")
    {
        answerNumber = a * c;
    }
    else if(b == "/")
    {
        answerNumber = a / c;
    }
    document.getElementById("input").value=answerNumber;
        }


    }       

I've tried reading up on various websites about Objects but they just are not helping at all, here are some of the places I went: "http://www.crockford.com/javascript/private.html" , "http://www.w3schools.com/js/js_objects.asp" among other places. For what I'm trying to do these do not seem to be very useful. Maybe some of you could help.

Here is the button and the text box that the object function will be trigger from and placed into:

<input type="button" value="   =    " name="enter" onClick="compute(this.form)">
<input name="display"  id="input" size=25>

Here is my entire sheet of code including the external JavaScript.

HTML:

<html> 
<head>
<title>Assignment 2</title>
</head>
<body>
<div align="center">
<span style="font-weight:bold" size="20">Calculator</span>
<br>
<!-- Prints my name -->
<form  name="MyName" id="form1" style="font-weight:bold" size="20">
<script>
document.write("Mallery, Cody");
</script>
</form>
<!-- Script -->
<script src="functions.js" type="text/javascript"></script>
<!-- The Calculator! -->
<center><form>
<table border=4>
<tr>
<td>
<input name="display"  id="input" size=25>
<br>
</td>
</tr>
<tr>
<td>
<input type="button" value="    7    " onClick="addChar(this.form.display, '7')">
<input type="button" value="    8    " onClick="addChar(this.form.display, '8')">
<input type="button" value="    9    " onClick="addChar(this.form.display, '9')">
<input type="button" value="    /    " onClick="addChar(this.form.display, '/')">
<br>

<input type="button" value="    4    " onClick="addChar(this.form.display, '4')">
<input type="button" value="    5    " onClick="addChar(this.form.display, '5')">
<input type="button" value="    6    " onClick="addChar(this.form.display, '6')">
<input type="button" value="    *    " onClick="addChar(this.form.display, '*')">
<br>

<input type="button" value="    1    " onClick="addChar(this.form.display, '1')">
<input type="button" value="    2    " onClick="addChar(this.form.display, '2')">
<input type="button" value="    3    " onClick="addChar(this.form.display, '3')">
<input type="button" value="    -    " onClick="addChar(this.form.display, '-')">
<br>

<input type="button" value="   0     " onClick="addChar(this.form.display, '0')">
<input type="button" value="    N    " onClick="changeSign(this.form.display)">
<input type="button" value="    +    " onClick="addChar(this.form.display, '+')">
<input type="button" value="   C   " onClick="this.form.display.value = 0 ">
<br>
<input type="button" value="   L    " name="L" onClick="Loop(this.form.display.value)" 
                                               title="If the L button is pressed, the digit present in the results box will be looped through and added up to the 'digit plus 10'.For example: After the calculator has been reset. The user can press the 1 button, then the L button 55 should be displayed in the calculator 1 + 10 = 11, therefore start with 1 and loop until less than 11 adding all of the numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55">
<input type="button" value="   =    " name="enter" onClick="compute(this.form)">
</td>
</tr>
</table>
<br>
<!-- Calculator User Guide -->
<span style="font-weight:bold" size="20">Instructions:</span>
<span size="16">
<br>Click a number, then an action, then another number, then the '=' button.
<br>Press 'C' when ready to start over. 
<br>The 'N' makes your previous number negative.
<br>The 'L' button requires one number to be avalible,
<br>It will loop through "that number" to "ten plus that number"
<br> and add all values and display.
<br>
<br>For example 1+2+3+4+5+6+7+8+9+10 = 55
</span>
<br><br>
<!-- Browser information -->
<span style="font-weight:bold" size="20">Navigator:</span>
<div id="Navigator"></div>

<script language="javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("Navigator").innerHTML=txt;

</script>
</form>           
</div>
</body>
</html>

External JavaScript:

/* gets the input from the keyboard OR clicking the button */
function addChar(input, character) 
{
if(input.value == null || input.value == "0")
    input.value = character;
else
    input.value += character;
}


/*changes the sign of the number inside the input box from negative to positive.*/
function changeSign(input) 
{
if(input.value.substring(0, 1) == "-")
    input.value = input.value.substring(1, input.value.length);
else
    input.value = "-" + input.value;
}


/*Computes the values inside the box and returns the answer.*/
function compute(form)  
{
    form.display.value = eval(form.display.value); /*The Calculator uses an Object for all calculations*/
}                


/* Loops the input by the value + 10 */
function Loop(input)
{
     var num = parseInt(input) + 10;
     var i=0;
     var sum=0;

    while(i < num)
        {
            sum=sum+i;
            i++;
        }
    document.getElementById("input").value=sum;

}

/*Compute Arithmetic*/
function calc() //creating an empty object named calc
{
}

var calc = new calc(); //creating a new instance of the calc object

calc.arithmetic = function maths (input) 
{
    var str = input;
    var a=str.substr(1,1); 
    var b=str.substr(2,1);
    var c=str.substr(3,1);

    if(b == "+")
    {
        answerNumber = a + c;
    }
    else if(b == "-")
    {
        answerNumber = a + c;
    }
    else if(b == "*")
    {
        answerNumber = a * c;
    }
    else if(b == "/")
    {
        answerNumber = a / c;
    }
    document.getElementById("input").value=answerNumber;
}

So any way that you can point me in the right direction is appreciated.

Upvotes: 0

Views: 4906

Answers (1)

Bergi
Bergi

Reputation: 665546

I don't know why you think you would need an object here. Just put them in a function - you have that maths function already. The code around it is only a syntax error.

Usually, by var myCalc = new calc(input); you create an instance of the calc constructor - it should not be followed by a function body. Also, by doing

function calc() {}
var calc = new calc();

you just overwrite the calc function with its instance - very strange.

If you want to namespace your functions, i.e. put them as properties onto an object (which is a good idea), you should use a simple Object literal. No need for a constructor function that would create multiple instances, you only need one:

var calc = {
   arithmetic: function maths (input) { … }
};
// then call
calc.arithmetic("1+3");
// which sets the input field to "4"

Upvotes: 1

Related Questions