I am still fairly new to Javascript and I am having some trouble getting a function to run properly. Here is what I have:
<script type='text/javascript'>
function GravityCalc (ratio, name)
{
Weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
</script>
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick='GravityCalc(2.3,Jupiter)'>calculate</button>
<div id='WeightText'> </div>
The form displays perfectly, but nothing happens when the button is pressed. It also should probably be noted that eventually, the name and ratio parameters is going to be parsed in with PHP.
-
2Look in the JavaScript error console. You'll see the errors there. (Hint: strings must be enclosed in quotes.)JJJ– JJJ2013年11月13日 22:11:31 +00:00Commented Nov 13, 2013 at 22:11
3 Answers 3
You have a couple things wrong...
- 'Weight' should be 'weight'. JS is case sensitive, and you had it in Camel case in one line and Pascal case in another line.
- You need to use 'document.getElementById'. Just 'getElementById' doesn't work in all browsers.
- You need to declare the 'Weight' variable.
- The value in a dom element is stored as a string or char array if you will, thus you need to parse it to an int, like so,
parseInt(document.getElementById('WeightBox').value)
Here's my JSFiddle... http://jsfiddle.net/EH5j6/
function GravityCalc (ratio, name)
{
var weight;
weight = parseInt(document.getElementById('WeightBox').value) * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
5 Comments
weight is NOT optional. Enter 08 in certain browsers to understand why.radix parameter in parseInt. Omitting it can lead to unexpected results.javascript variables are case sensitive! Your Ws didn't match up. I also highly recommend using var to explicitly declare your variables.
var weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
plus, as a commenter noted, strings must be enclosed by quotes.
<button onclick='GravityCalc(2.3,"Jupiter")'>calculate</button>
Comments
Make sure that you include the javascript in the head of the html page.
function calc (ratio, name) {
var weight = document.getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = "You would weigh " + weight + " on " + name;
}
and change the HTML to be:
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick="calc(2.3, 'Jupiter')">calculate</button>
<div id='WeightText'> </div>