0

Each time submit button is clicked, I would want the Experience to increment by 1. I have declared Experience as global variable, however the Experience does not go beyond 2.

<html>
<head>
<script>
var Experience = 1;
function scenario1()
{ window.Experience = window.Experience + 1 ;
    alert(window.Experience);

}
</script>
</head>
<body>
<form>
<input type="submit" onclick="scenario1()">
</form>
</body>
</html>
1
  • 1
    The Problem is Post back, once you click the button it will increment the value , then it post back so page reload happens, and the value sets to 1, so you need to prevent postback. DEMO jsfiddle.net/mbanandetoro6/7SBKp Commented Jun 21, 2014 at 3:43

3 Answers 3

4

Open up your developer tools and watch the network tab.

When you click the submit button, it will:

  • Run your function.
  • Reload the page
    • Reset the variable.

You need to prevent the page from submitting.

There are two approaches.

Approach 1: Prevent the submit

<html>
  <head>
    <script>
      var Experience = 1;
      function scenario1() {
        // Shorthand way to write it
        window.Experience++;
        alert(window.Experience);
      }
    </script>
  </head>
  <body>
  <form>
    <input type="submit" onclick="scenario1(); return false">
   </form>
  </body>
</html>

Approach 2: Use a button that doesn't submit

<html>
  <head>
    <script>
      var Experience = 1;
      function scenario1() {
        // Shorthand way to write it
        window.Experience++;
        alert(window.Experience);
      }
    </script>
  </head>
  <body>
  <form>
    <button type="button" onclick="scenario1()">Do it</button>
   </form>
  </body>
</html>

Extra notes

Lots of global variables is generally a pretty bad idea. If this is for a game of some sort, you'd be better putting everything into a player object.

var player = {
  experience: 0,
  name: "Just some guy"
};

// Grant experience
player.experience += 10;
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of

<input type="submit" onclick="scenario1()">

try this:

<input type="button" value="click!" onclick="scenario1()">

That way your browser won't try to post something and hit an error.

Comments

0

There actually isn't anything wrong with this. It works, you just need to not use a submit button. Try just a regular input button: see here

<input type="button" onclick="scenario1()" value="Submit">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.