...

View Full Version : Simple calc with eval



TehMadHatter
01-23-2012, 04:52 AM
<HTML>

<HEAD>

<TITLE>John's JavaScript!</TITLE>

<SCRIPT TYPE="text/javascript">

function solve(math)
{
form.answer.value = eval(math);
}

</SCRIPT>

</HEAD>

<BODY>

<FORM METHOD="POST">
Enter a JavaScript mathematical expression:
<INPUT TYPE="text" NAME="entry" VALUE="" />
<BR />
The result of this expression is:
<INPUT TYPE="text" NAME="answer" VALUE=""
onFocus="blur()"/>
<INPUT TYPE="button" NAME="submit"
onClick="solve(form.entry.value)"/>

</BODY>

</HTML>


The only problem I am facing is changing form.answer.value
It won't change, why not?

Old Pedant
01-23-2012, 07:02 AM
Because you are using form. without ever giving a value to the variable form

A better way to do this:


<form onsubmit="return false;"><!-- ensure this form can't actually be submitted -->
Enter a JavaScript mathematical expression: <input name="entry" />
<br/>
The result of this expression is: <input readonly="readonly" name="answer" />
<br/>
<input type="button" name="submit" onclick="this.form.answer.value=eval(this.form.entry);" />
</form>

By the by:
(1) UPPER CASE tag and property names are obsolescent in modern xhtml, which almost everybody now users.
(2) If you don't have a </form> tag, then you can never refer to form elements via form.

If you insist on moving the JS code to the <head>, then you will need to "find" the <form>, so:


function solve( math )
{
var form = document.forms[0];
form.answer.value = eval( math );
}

and

<input type="button" name="submit" onclick="solve(this.form.entry.value);" />
or
<input type="button" name="submit" onclick="solve(document.forms[0].entry.value);" />





[/code]

felgall
01-23-2012, 09:47 AM
One thing to note is that your code will not just EVALuate calculations. It will also run scripts that will be able to do anything they like to the web page.

You should NEVER use eval in JavaScript in web pages that you expect anyone other than you to have access to.

cuzMazn
01-23-2012, 05:40 PM
One thing to note is that your code will not just EVALuate calculations. It will also run scripts that will be able to do anything they like to the web page.

You should NEVER use eval in JavaScript in web pages that you expect anyone other than you to have access to.

Hi,

The only way I know to calculate a string is to use eval() OR looping through each of the units in the string and use isNaN function to calculate it. Using eval() sounds more simple and realistic. However, you should make sure that the input is a valid operation by running Reg Test:



var $string = "1+2+2*4";
$string.replace(/[^-()\d/*+.]/g, '');
$result = eval($string);


I hope this help.

Tim._

felgall
01-23-2012, 07:37 PM
That expression should prevent most attacks and will also block any calculations that require the use of the Math object.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum