-1

I created a small function that causes a number to increase based on clicks. I originally did it all on one file, but I now need to separate it into separate files because I want to use the function as part of my game. Unfortunately, I'm relatively new to Javascript, and I must have messed up somewhere. Here's what I have:

HTML:

<body>
    <button type="button" onclick="increaseMainScore()" id="mainPostCard"></button>
    <input type="text" id="outputScore"></input>
</body>

JS:

var mainScore = 1;

function increaseMainScore() {
    var textBox = document.getElementById("outputScore");
    textBox.value = mainScore;
    mainScore++;
}

Also with some CSS test styling and such.

JSfiddle where it works(single page): http://jsfiddle.net/bSt2u/

JSfiddle where it doesn't work: http://jsfiddle.net/AdG8Y/

If anyone could help me solve the issue, that'd be great.

1 Answers1

1

You may try something like this, you have to keep this code either in your page between script tags inside head like (simplest one)

<head>
    <script type="text/javascript">
        window.onload = function(){
            var mainScore = 1;
            var btn = document.getElementById('mainPostCard');
            btn.onclick = function(){
                var textBox = document.getElementById("outputScore");
                textBox.value = mainScore;
                mainScore++;    
            };
        };
    </script>
</head>

Or keep this code in a separate .js file, i.e (yourfile.js) and add it in the HTML page using (inside head tags)

<script type="text/javascript" src="yourfile.js"></script>

Also, check this answer.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307