My first day of Javascript and I am incredibly confused. I am passing numbers returned from a form to a function, but the result is not consistent with what it should be. My testing leaves a lot to be desired, but hopefully the following makes sense.
The function g calculates the sum of the sequence.
<form name="gaussform">
<input name="min"
type="number"
min="1"
value="1">
<input name="max"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="alert_g()"
type="submit"
value="calculate">
</form>
<script type="text/javascript">
function g(min,max,step) {
var actualmax = max - ((max - min) % step)
return (min + actualmax) * ((1 + ((actualmax - min) / step)) / 2)
}
function alert_g() {
var frm = document.forms["gaussform"]
var min = frm["min"].value
var max = frm["max"].value
var step = frm["step"].value
if (min == 1) {
alert("min is 1")}
if (max == 10) {
alert("max is 10")}
if (step == 1) {
alert("step is 1")}
alert(g(min,max,step))
// below returns the desired result
alert(g(1,10,1))}
</script>
the if statements are only so I can understand what is going on!
So if the user enter 1,10,1 (the default values) the result should be 55.
alert(g(1,10,1)) -> 55
alert(g(min,max,step) -> 550
alert(g(1,100,2)) -> 2500
alert(g(min,max,step) -> 4975 (obviously min,max,step == 1,100,2)
the function g is correct, but I do not understand what is happening to the values that are being passed to it.
This expression…
…is the problem.
You probably want to make that…
…or use
parseFloat(),parseInt()or whatever suits your requirements to turn those strings into an actualNumber.jsFiddle.
JavaScript’s
+operator is overloaded for arithmetic addition and string concatenation. Because user input is always a string, you’re doing string concatenation.