Reputation: 1593
I have a javascript function to calculate total amount :
<script>
function calculate(v)
{
v = parseFloat(v);
v = v + 19;
//alert(v);
document.write.getElementById("total") = v;
}
</script>
which is within <head></head>
section . I am calling this function from :
Select amount you want to buy : <input type="text" name="qty" onkeyup="calculate(this.value)"/> grams
And I am trying to display value of v
here :
<div id="total"><script> document.write(v);</script></div>
But it is not showing anything. Why?
Upvotes: 1
Views: 3553
Reputation: 88
document.write
only works on an "open" document. When the end of the file is reached, the document is closed for writing (at least through those outdated means). I believe most browsers will just ignore an attempt to write to a closed document, but some may throw an error.
Other issues at hand here are that you are not calling document.write()
but trying to access yet another field (or child) of that function, getElementById
, which doesn't exist.
Finally, in your last bit of code, you are attempting to write the value of v
which is a local variable to the calculate()
function so it doesn't really exist outside that scope.
A few other people have already pointed out remedies to this, namely document.getElementById('total').innerHTML = <your value>
. Accessing innerHTML
is not the cleanest way to do things, but it works in all major browsers and is easy to understand.
Hope that a little bit of explanation about what was going is helpful. Good luck! (Think about learning one of the many javascript frameworks if you get much further into it -- they can be a great help. Prototype.js, jQuery, Dojo, MooTools, etc., are all good.)
Upvotes: 4
Reputation: 1120
: incorrect document.write.getElementById("total") = v;
document.getElementById("total").innerHTML = v;
Upvotes: 0
Reputation: 490637
You have a misunderstanding of how document.write()
works.
You probably want...
var elem = document.getElementById("total");
if (elem.textContent) {
elem.textContent = v;
} else {
elem.innerText = v;
}
Upvotes: 3
Reputation: 1894
you can do this
document.getElementById("total").innerHTML = v;
document.write(v);
Upvotes: 1
Reputation: 8887
//document.write.getElementById("total") = v;
document.getElementById("total").innerHTML = v;
Upvotes: 1
Reputation: 449803
document.write.getElementById("total") = v;
This is not how document.write
works and will throw an error in the JavaScript console. Always make sure you check the console for possible errors first.
You are looking for .innerHTML
.
Upvotes: 1