craig2014
craig2014

Reputation: 3

Thwarted by document.write in Javascript

I have a javascript function that does a lovely job of drawing a row of boxes of a given number based on the value of a form element called NumOTurns in a specific place on a web page. But it only does this lovely job when the page loads. If I call the function (in order to change the number of boxes), then document.write rewrites the entire page -- not what I want!

Here is the js as it currently stands:

<script>
function buildTurns() { 
    GAMELENGTH=Number(document.getElementById("NumOTurns").value);
    for (turnCount=2;turnCount<(GAMELENGTH)+1;turnCount+=1) {
        document.write("<div class='turnBox' id='Box"+(turnCount)+"'>"+(turnCount)+"     </div>")
    }; 
    if (GAMELENGTH != Math.floor(GAMELENGTH)) {
        document.getElementById("Box"+Math.ceil(GAMELENGTH)).style.background="url(images/halfturn.png) no-repeat center";}
    }
</script>

The default value of NumOTurns is 12 so when the page loads I get 11 boxes drawn (added to one pre-exisiting static box). But if I enter 6 into NumOTurns and call the function then document.write just overwrites the page with boxes 2-6 (sans the CSS so all you see is the numbers 2-6).

I know document.write is the villain here. How can I achieve my goal of being able to change the number of boxes drawn after the page is loaded???

Weird Hint: In Firefox and Firefox only, if I change the value of NumOTurns and then click FF's reload icon, I get the result I want. Doesn't happen in any other browser though.

Upvotes: 0

Views: 78

Answers (1)

KooiInc
KooiInc

Reputation: 122888

document.write opens a new DOM and that only works on page load. It's very outdated. You could rewrite your javascript to (don't forget to put the script tag at the end of the page, right before the closing </body> tag):

var GAMELENGTH = +(document.getElementById("NumOTurns").value);
for (turnCount=2;turnCount<(GAMELENGTH)+1;turnCount+=1) {
        var nwbox = document.createElement('div');
        nwbox.className = 'turnBox';
        nwbox.id = 'Box'+turnCount;
        nwbox.textContent = turnCount;
        // or nwbox.innerHTML = turnCount;
        document.body.appendChild(nwbox);
}; 
if (GAMELENGTH != Math.floor(GAMELENGTH)) { /* etc */ }

Upvotes: 1

Related Questions