The Journal of Online Mathematics and Its Applications, Volume 7 (2007)
Creating Mathlets with Open Source Tools, Markus Hohenwarter and Judith Preinder

Writing a JavaScript Function

Below you find the JavaScript code for our function check() that checks whether the entered equation is correct. Our GeoGebra construction contains several objects to help us with checking the user input in JavaScript. The construction includes the function f(x), its derivative h(x) and a function g(x) = 0 that the user will be able to change using the input field on the web page. Furthermore, we have added a function diff(x) = Polynomial[ h(x) - g(x)] that shows the difference of the derivative h(x) and the user's answer g(x) as a polynomial in standard form. Thus, we only need to check if diff(x) = 0. Both h(x) and diff(x) are hidden objects in the GeoGebra construction.

1. <script>
1. function check() {
2.
3.    var applet = document.ggbApplet;
4.    applet.evalCommand("g(x) = " + document.inputform.textfield.value);
4.    var diffString = applet.getValueString("diff");
5.    if (diffString == "diff(x) = 0") {
6.        alert("Good job! That's correct!");
7.        applet.setVisible("h", false);
8.     } else {
9.        applet.setVisible("h", true);
10.        alert("Your solution is not correct. Compare your solution with\n
           the red graph of the derivative and try again.");
11.    }
12. }
13.
14. </script>

The first and last lines are the beginning and end of the JavaScript block in our HTML page which need to surround our declaration of the check() function. In line 4 we take the user's input to set the hidden function g(x). Then we get the equation of diff(x) and check whether it's 0, i.e. if the the user entered the correct solution (line 6). In case of a wrong answer we show the graph of the solution h(x) to provide some feedback about the mistake (lines 10-12). If the answer was correct, we make sure that our hint, the graph of the derivative h(x), is hidden again (lines 7-8).