jblittle
jblittle

Reputation: 135

Using innerHTML to write to page but it quickly disappears

I am trying to make my page so that when I enter a number and click submit, right below it something like "You guessed number" shows up. It does this, but only for a split second before disappearing. I would like it to stay until I click the submit button again. What exactly is the issue?

Relevant HTML

<form id="form" onsubmit="returnGuess()">
Enter your guess: <input id="guessbox" type="text" name="userguess">
<input id="submitbutton" type="submit" value="Submit">
</form>

<p id="yourguess"></p>

The

is where I'd like it to go.

Relevant JS

function returnGuess() {
    var guess = document.forms["form"]["guessbox"].value;
    document.getElementById("yourguess").innerHTML = "You guessed " + guess;
}

Basically I'm just asking how I can make the updated text stay there.

Upvotes: 0

Views: 837

Answers (3)

ps2goat
ps2goat

Reputation: 8475

returnGuess is your onsubmit action for the form. So when you click the submit button, your code runs and then the form is posted back to the server. It looks like the page posts back to itself and returns the new page, thus your guess is lost.

I would not even use the form tag with a submit button. Just use a regular button if you aren't posting back:

Enter your guess: <input id="guessbox" type="text" name="userguess">
<input id="submitbutton" type="button" value="Submit" onclick="returnGuess();">


<p id="yourguess"></p>

And keep the script the same, though I'd use innerText instead of innerHTML if you don't want to change the html.

function returnGuess() {
    var guess = document.forms["form"]["guessbox"].value;
    document.getElementById("yourguess").innerHTML = "You guessed " + guess;
}

Upvotes: 0

William Newby
William Newby

Reputation: 621

The issue is that you are using a submit button, so the page is posted to your server and then re-rendered. If you want to show them the number they entered and submit the form, you are going to need to write it to your html output when handling the submit server-side

Upvotes: 1

David
David

Reputation: 34563

The problem is that your page is being reloaded because your form sends the data to the server when you click submit.

You need to cancel the form submission from your javascript. This other question has more discussion about doing this: How do I cancel form submission in submit button onclick event?

I would try changing your <form> tag to this:

<form id="form" onsubmit="return returnGuess()">

and then add return false; to the end of your javascript method.

Upvotes: 1

Related Questions