Page 1 of 1

real-time text update via javascript

Posted: Thu Oct 23, 2003 4:46 pm
by microthick
In the past, whenever implementing things like "Price Calculators" in JavaScript, my calculated "Cost" would appear in a text form field so that I could update the cost as the user fills out the form, rather than having to submit the page.

Is it possible to update text on the screen using JavaScript without displaying the calculated value in a form field?

I assume it has to be done by using the DOM but I don't have much experience in that area.

Might someone be able to prototype an example?

Posted: Thu Oct 23, 2003 5:40 pm
by Gen-ik
Using object.innerHTML will do the trick but not all browsers can use it which is a damn shame. I think it's IE5.5 (or higher) and NS6 (or higher)... not sure about the other "lesser" browsers out there.

Here's an example using innerHTML though.

Code: Select all

<html>
<head>

<script language="javascript">

function UpdateSpan(text)
&#123;
     if(!document.body.innerHTML) return; // Stops the function if innerHTML can't be used

      if(document.layers)
      &#123;
            document.TheSpan.innerHTML = text;
      &#125;
      elseif(document.getElementById)
      &#123;
            document.getElementById('TheSpan').innerHTML = text;
      &#125;
      elseif(document.all)
      &#123;
            document.all.TheSpan.innerHTML = text;
      &#125;
&#125;

</script>

</head>
<body>

<span id="TheSpan">Some text</span>
<br>
<a href="javascript:UpdateSpan('some new text')">insert new text</a>

</body>
</html>
.......haven't tested it but it should do the trick.