PDA

View Full Version : evaluate an expression


trungluu
07-30-2003, 05:24 AM
Hi,

In Javascript I can use the eval() function to evaluate an expression (ex: 10+2*5 ...) But I don't know how to check the data that are entered by user is valid for eval() function. If user type 10+aa+2 the eval() function will fire an error. Could you please tell me how to check the input data of user. I try to use a try{...}cacth(e){} statement but it's not work well.

Thanks in advance,

Trung Luu

scriptkeeper
07-30-2003, 05:26 AM
Try this

<html>
<head>
<script>
function calculate(){
val_1=parseInt(document.exp.int1.value);
val_2=parseInt(document.exp.int2.value);
try{
if(isNaN(val_1)||isNaN(val_2)){
throw "Enter Only Numbers Please?";
}
else{
ans=val_1+val_2
alert("The Answer is: " + ans);
}
}
catch(e){
alert(e);
}
}

</script>

glenngv
07-30-2003, 06:46 AM
I think this is what trungluu needs:


<html>
<head>
<script>
function doEval(){
try{
document.myform.result.value = eval(document.myform.expr.value);
}
catch(e){
alert(e.message)
}
}

</script>
</head>
<body>
<form name="myform">
Enter mathematical expression:<br>
<input name="expr"> = <input name="result">
<input type="button" value="Evaluate" onclick="doEval()">
</form>
</body>
</html>


This is probably the only use of eval() function. Other programmers misuse and abuse it. :D

scriptkeeper
07-30-2003, 07:34 AM
Ok I dont use eval its Evil! JK I have never really used it before but the script seems pretty neat! I always heard eval causes problem/errors! But it seem to work fine here!

glenngv
07-30-2003, 08:50 AM
I don't use it too! :)
eval is evil if you don't use it properly :D

jkd
07-30-2003, 12:16 PM
If you're evaluating mathematical expressions, I personally prefer:

var f = Function('', 'return ' + str);

and then calling f() (potententially with x and/or y arguments).

trungluu
07-31-2003, 11:39 AM
Hi All,

Thank you very much for your help

Trung Luu