Enable javascript on google sites

I am trying to include simple javascript in Google Sites, but I get nothing when I click a button. I put the code inside an HTML window. When checking locally, the code works fine. Here is my code:

<script> function calcul(){ x = parseFloat(document.getElementById("value1").value); y = parseFloat(document.getElementById("value2").value); document.getElementById("answer").innerHTML=x+y; } </script> <form action="" id="nothing"> <input type="text" id="value1"> <input type="text" id="value2"> <input type="button" value="Calculate" id="but" onclick="calcul()" /> <p id="answer"></p> 

Is there something that I forgot to make it work?

+6
source share
2 answers

Google sites will change your entire script. You should be a little careful when writing JavaScript.

Adding var before each variable will fix your problem:

 <script> function calcul(){ var x = parseFloat(document.getElementById("value1").value); var y = parseFloat(document.getElementById("value2").value); document.getElementById("answer").innerHTML=x+y; } </script> <form action="" id="nothing"> <input type="text" id="value1"> <input type="text" id="value2"> <input type="button" value="Calculate" id="but" onclick="calcul()" /> </form> <p id="answer"></p> 

This will work; -)

+5
source

Google sites will filter out activities that it considers unsafe. Some details are here , but could not find official documentation with a quick search.

As another answer is mentioned, your variables require var declarations. This is necessary because without this, the variables will become global for the window and could potentially be used to exit any Google sandbox that hosts javascript support on sites, which can cause security problems.

So, to fix:

 var x = parseFloat(document.getElementById("value1").value); var y = parseFloat(document.getElementById("value2").value); 
+1
source

All Articles