PDA

View Full Version : execute a maunal math equation


JackFruit3D
09-29-2002, 12:46 AM
I am wanting to type in a math equation into a text box and then onblur (onblur="") execute the equation that is typed into the box and place the result into another text box.

I am not sure how to do this as all my experimenting has resulted in simple text string additions.... if that made sense.

chrismiceli
09-29-2002, 12:52 AM
you could do this

function test() {
result = eval(document.form1.text.value);
document.form1.result.value = result;
}


<form name="form1">
<input type="text" name="put" value="" onBlur="test()">
<input type="text" name="result" value="">

if this don't work tell me.

whammy
09-29-2002, 12:56 AM
The problem there lies in the fact that not only is "+" a mathematical addition operator, "+" is also used in javascript to concatenate strings!

So unless you let javascript know otherwise (by performing a different mathematical operation on the string (i.e. multiplication or division), or use the Number() function), it will just concatenate the values.

I hope that makes sense... I know how it works even if I don't know how to explain it well. Here's an example that should make it clear:


<form name="form1">String:
<input type="text" name="one" value="1" size="1" />+<input type="text" name="two" value="2" size="1" />=<input type="button" value="?" onclick="alert(this.form.one.value + this.form.two.value)" />
</form>

<form name="form2">Number:
<input type="text" name="one" value="1" size="1" />+<input type="text" name="two" value="2" size="1" />=<input type="button" value="?" onclick="alert(Number(this.form.one.value) + Number(this.form.two.value))" />
</form>

<form name="form3">Number:
<input type="text" name="one" value="1" size="1" />+<input type="text" name="two" value="2" size="1" />=<input type="button" value="?" onclick="alert(this.form.one.value*1 + this.form.two.value*1)" />
</form>



;)

jkd
09-29-2002, 02:07 AM
I used this to dynamically create one-variable mathematical functions from user input:

var f = Function('x', 'return ' + userInput);

// then use like f(10);

:)