Including javascript to google sites
Asked Answered
W

2

6

I'm trying to include a simple javascript to Google Sites but I get nothing when pressing the button. I put the code inside an HTML Box. The code works perfectly when tested locally. 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 I forgot to make it work?

Wardwarde answered 8/2, 2013 at 20:30 Comment(2)
Can you give us a link to the the live site?Trigeminal
Sorry, I can't. It's a private site and the owner doesn't want to give acces.Wardwarde
V
5

Google Sites changes your entire script. You have to be a bit more careful writing JavaScript.

Adding var in front of every 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 ;-)

Veratrine answered 8/2, 2013 at 20:44 Comment(4)
Thanks about the var bit (and to @ben336 for the explanation). Unfortunaly that didn't solve the problem, I still get nothing when clicking that button.Wardwarde
Have you inserted the code in a HTML box? (Insert -> HTML box)Veratrine
There is a problem when you visit the page logged in as an administrator. View the page as viewer (More -> Preview page as viewer). Should work there.Veratrine
Well that was it! Thanks a lot, you just made my day :)Wardwarde
I
1

Google Sites will filter out operations it considers unsafe. Some details here, but was unable to find official documentation with quick search.

As another answer mentions, your variables need var declarations. This is required because without this, the variables will become global to the window, and potentially could be used to escape whatever sandbox Google is putting around the sites javascript support, potentially causing security concerns.

So to fix:

var x = parseFloat(document.getElementById("value1").value);
var y = parseFloat(document.getElementById("value2").value);
Irrelevant answered 8/2, 2013 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.