Reputation: 293
I have some javascript that is returning the word count of a text field into a 'wordcount' var.
I'd like for the 'wordcount' var (and other variables based on it) to be displayed throughout my HTML. But in a way where they can be constantly updated as the word count changes.
e.g. Your current wordcount is 10. You have 5 remaining words. The current cost is £10 (£1 / Word).
I'm relatively new to the wonders of JavaScript, but I've picked up the following from what I've read online...
document.write
is frowned upon.getElementById
will only allow me to display each variable once..data
functionality that stores (and updates?) data
locally?Can anyone please point me in the right direction?
Thanks, Andy.
Code as requested...
<!DOCTYPE html>
<html>
<head>
<title>Word Count Test</title>
</head>
<body onload="countnow()">
<form method="POST" name="counter">
<script language="JavaScript">
var freebie_words = 15
var base_price = 10.00
var word_price = 0.50
var wordcount = 0
var additional_words = 0
function countnow(){
var formcontent=document.counter.userscript.value
var formcontent=formcontent.split(" ")
var wordcount=formcontent.length
var freebie_remaining=freebie_words-wordcount
if (wordcount>freebie_words)
{
additional_words=wordcount-freebie_words
} else {
additional_words=0;
}
if (wordcount<freebie_words)
{
cost=base_price.toFixed(2);
} else {
cost=(base_price+(additional_words*word_price)).toFixed(2);
}
document.getElementById("freebie_words").innerHTML = freebie_words;
document.getElementById("base_price") = base_price;
document.getElementById("word_price") = word_price;
document.getElementById("wordcount") = wordcount;
document.getElementById("freebie_remaining") = freebie_remaining;
document.getElementById("cost") = cost;
}
</script>
<table>
<tr>
<td width="100%">
<textarea rows="10" name="userscript" cols="60" onkeyup="countit()"></textarea>
</td>
</tr>
</table>
The base price is set to £<span id='base_price'></span> for <span id='freebie_words'></span>.<br>
The base price limit is set to <span id='freebie_words'></span>.<br>
You have typed <span id='wordcount'></span> words.<br>
You have <span id='freebie_remaining'></span> free words left.<br>
That will be £<span id='cost'></span>.
</form>
</body>
</html>
Upvotes: 1
Views: 405
Reputation: 28837
Conceptually you can do this:
wordcount
changes.$('.mychangeclass').text(wordcount);
If you post some html I can answer adapted to your code.
Upvotes: 3