1

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?

0

6 Answers 6

4

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.)

Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

1 Comment

But the element in question is a div?
1
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.

Comments

1
//document.write.getElementById("total") = v;
document.getElementById("total").innerHTML = v;

Comments

1
you can do this

 document.getElementById("total").innerHTML = v;

 document.write(v);

Comments

0

: incorrect document.write.getElementById("total") = v;

document.getElementById("total").innerHTML = v;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.