Reputation: 14559
I'm trying to have a value (key
) that updates to correspond with a number in a textbox (angle
) divided by a value (25
). However, for some reason, the changeMe
function doesn't seem to be executing. Am I using onchange incorrectly?
<script type="text/javascript">
function changeMe(x)
{
var y=document.getElementById(x).value;
y = (y/25);
y = (Math.round(y));
document.getElementById(key).value=y;
}
</script>
<form method="POST" action="">
Your Angle: <input type="text" name="angle" id="angle"
onchange="changeMe(this.id)" value="0"/>
Key: <span id="key">0</span><br />
</form>
Upvotes: 0
Views: 407
Reputation: 23
Try using the suggestion by James Black to use onchange="changeMe(this)"
, your function becomes simplified
function changeMe(x) {
y = Math.round(x.value/25);
document.getElementById('key').innerHTML = y;
}
Notice the document.getElementById('key').innerHTML = y
, This will replace the inner html (as the name describes), I think that is what you wanted to use.
Upvotes: 0
Reputation: 361615
The last line document.getElementById(key)
should be document.getElementById("key")
.
By the way you can simplify this a fair bit by passing the <input>
element directly instead of its id:
<script type="text/javascript">
function changeMe(angle)
{
var key = document.getElementById("key");
key.innerHTML = Math.round(angle.value / 25);
}
</script>
<form method="POST" action="">
Your Angle: <input type="text" name="angle" id="angle"
onchange="changeMe(this)" value="0"/>
Key: <span id="key">0</span><br />
</form>
Upvotes: 1
Reputation: 11596
Change the line
document.getElementById(key).value=y;
to
document.getElementById('key').innerHTML=y;
Upvotes: 5
Reputation: 41858
The changeMe(this.id)
bothers me, I am using to seeing just (this)
, but, the best way to know what is going on is to use either the Web Developer extension in IE8 (I press F12 and it comes up) or, preferably, Firebug, on Firefox, and then you can put in a break point at the beginning of the changeMe function and see what is passed in, as there may be an error.
And the other two already mentioned about the problem with your getElementById.
Upvotes: 1
Reputation: 25147
To see if it's being called, just add this as the first line:
alert("Hey, I'm being called!");
Now, I already see a problem here: in the last line of your function, you're doing getElementById(key)
, but you should enclose key
with double quotes. If not, it's being considered a variable instead of a string.
Upvotes: 1