Andy Cheeseman
Andy Cheeseman

Reputation: 293

One changing JavaScript variable being displayed (and updated) in multiple locations in HTML

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

  1. document.write is frowned upon.
  2. getElementById will only allow me to display each variable once.
  3. jQuery has a .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 &#163;<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 &#163;<span id='cost'></span>.
</form>

</body>
</html>

Upvotes: 1

Views: 405

Answers (1)

Sergio
Sergio

Reputation: 28837

Conceptually you can do this:

  • Create a function that fires when your wordcount changes.
  • Give a class to all elements (span, div, etc) that have the text/number you want to update.
  • With jQuery you can then use inside your function: $('.mychangeclass').text(wordcount);

If you post some html I can answer adapted to your code.

Upvotes: 3

Related Questions