I’m trying to use the following code to grab the variables from the two inputs and add them together using Coffeescript like so:
here’s the HTML…
<form action="" method="GET">
<input type="text" name="input1" value="2">
<input type="text" name="input2" value="3">
<input type="button" name="button" value="Equals" onClick="math(this.form)">
<span id="result" />
</form>
And the javascript…
math = (form) ->
input1 = form.input1.value
input2 = form.input2.value
document.getElementById("result").innerHTML = parseInt(input1, 10) + parseInt(input2, 10)
However, it’s not outputting anything on the page. When I click the button, the Console tells me that “math” is not defined (on the fourth line of the html code.)_
You guys know what’s going wrong here?
Coffeescript has inherent scope.
It made math a local variable in a wrapper by default, thus you need to explicitly define window.math to access it from the rest of the webpage.
Coffeescript really is better when you’re using some sort of javascript selector engine, wether that be native or jQuery, etc.