0

I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in

var special=(10000-health);
var health=(100);

<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />

this just writes "special" to the box, when I would like the value instead.

expiredninja
  • 1,397
  • 4
  • 25
  • 45
  • You're referencing `health` before it's defined. You might want to move `var health=(100);` above the declaration of `special`. – Rob Sobers Dec 13 '10 at 03:01

4 Answers4

5

You have to set the value explicitly:

document.getElementById('special').value = special;

Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.

Update: Here is an example:

<body>
    <input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />

    <script type="text/javascript">
        var health = 100;
        var special = 10000 - health;
        document.getElementById('special').value = special;
    </script>
</body>

References: getElementById, DOM

MDC's JavaScript Guide is also worth reading.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1
document.getElementById('special').value = special;
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

you have to use some kind of DOM manipulation. One of the more popular libraries is JQuery.

using jQuery you'd write something like

$('#special').val(special);

Al W
  • 7,539
  • 1
  • 19
  • 40
0
var input = document.getElementById('special');
input.value = special;
sweetier
  • 131
  • 1
  • 3
  • 11