0

I've created a game which guesses a number. My current problem is that each time I click the guess button, the number refreshes itself! How can I stop this happening? I've been labouring over it for a while now but no luck, I'm still new to javascript. Answers with an explanation of what I did wrong would be much appreciated, because at the moment I can't see why it's doing that.

<form id='sampleform' method='get' action=''>

Guess: <input type='text' name='guess' id = 'guess'/>

<button id ='b1' name='Submit' value='Submit'/>

</form>



<script>

document.getElementById("b1").addEventListener("click", checkForm);

x = Math.floor(Math.random()*99)

function randomNumber(){
    return x;
}


function checkForm(){

var number = document.getElementById('guess').value; 
if (number == null || number == "" || isNaN(number) || number < 0 || number > 99){

    alert("Invalid input");
    return false;
}

else if (number == x)
{
    alert("You're correct!");
    document.getElementById('b1').disabled = true;
    return true;
}

else{

    alert("Wrong! Try again.")

    }
}

randomNumber();
console.log(x); //checks value for testing

</script>

kx k
  • 1
  • what do you actually want to happen ? (generate random number only once or anything else ) – J Santosh Aug 29 '15 at 18:01
  • 1
    It's because when you submit the form, the browser will load the page specified by the 'action' form attribute. That's the same page (since it's empty), so it refreshes, which runs your script again. You could use ajax, go to a different page, or pass a query param that tells you it's a reload. – sje397 Aug 29 '15 at 18:01
  • 2
    When you submit a form, the page will reload. Since you don't seem to be using the form for anything, you can remove it. – deleted user Aug 29 '15 at 18:07

3 Answers3

2

You could solve this issue by stopping the submit event of the form with Event.preventDefault():

document.getElementById("sampleform").addEventListener("submit", function(event){
    event.preventDefault();
});

As mercator points out, if you use an empty string for your action attribute, it will use the document's address and in further consequence reloads your script.

Community
  • 1
  • 1
Matthias A. Eckhart
  • 5,136
  • 4
  • 27
  • 34
1

Assuming that you want to submit the form to the server.

You can generate a value and store it in the browser's localStorage, and use that value if it is already defined.

if (localStorage['random-number']) {
  x = parseInt(localStorage['random-number']);
} else {
  x = Math.floor(Math.random() * 99);
  localStorage['random-number'] = x;
}
toskv
  • 30,680
  • 7
  • 72
  • 74
  • It didn't even occur to me to use localStorage, I probably won't be implementing it just this second as I haven't looked into it enough but I'll definitely play with it in the near future! Thanks. – kx k Aug 29 '15 at 21:13
  • np. just as a note, the user can see what is stored in localStorage. It might not be the best place to store it if you want to keep the user from seeing it. :) – toskv Aug 29 '15 at 21:15
0

Well, I see different things here, so I will try to explain as clearly as possible every point.

First:

<button id ='b1' name='Submit' value='Submit'/>

You haven't specified a type for the button ("submit", "button" or "reset"). By default (depending of the browser) the type will be set to "submit", which posts the current form to the url set in the "action" attribute, hence re-calculating your hidden number. And by the way, you don't need to set a name to the button if you are selecting it by id in the javascript code.

So, setting the type="button" gives you the chance to set the behavior of the button without triggering any other event.

Second:

Ok, now the button doesn't submit the form and the number is not refreshed, but... what if the user enters a number and hits Enter? The form is posted.

Well, you have 2 ways to solve this: you disable the submit event or just not using a form, since you do everything through Javascript. If you really want to use a form, you must consider the "onsubmit" event.

Finally,

I will give you 2 ways to solve this:

1) Using the form and handling the onsubmit event: http://jsfiddle.net/q620qaun/

2) Not using the form and using a dummy button: http://jsfiddle.net/019xL737/1/

Hope that it helps! good luck!

  • That piece of code has made preventDefault click with me. I was reading up on it but was still slightly confused. Everything seems to make so much more sense when you apply it to your own piece of work. Thanks a bunch for the answers! I'll be looking into dummy buttons too. – kx k Aug 29 '15 at 21:16