1

Whenever I click on the button I get the output for a second in the text-field "Result" and then it's gone.. why does it disappear? (I have tried to place the function in the body.. it doesn't help..)

<html>
    <head>
        <script>
            function someFunction()
            {
                with (document.formy)
                {
                    resultsBox.value= "In " + yearsBox.value + "you will be" + ageBox.value + yearsBox.value +" years old.";
                }
            }
        </script>
    </head>

    <body>
        <form name="formy">
            Enter your current age: <input id="ageBox" type="text" value="18" />
            <br/>
            Enter number of years: <input id="yearsBox" type="text" value="5" />
            <br/>
            Click this button: <button onclick="someFunction()">Click me!   </button>
            <br/>
            Results: <input id="resultsBox" type="text" />
        </form>
    </body>
</html>
Soma
  • 857
  • 2
  • 17
  • 32
Ohad
  • 1,381
  • 2
  • 14
  • 34

3 Answers3

3

The default type for buttons is submit. When you click the button the form is submitting and reloading the page. You can avoid this by setting the type attribute on the button:

<button type="button" onclick="someFunction()">Click me!</button>
Bic
  • 2,981
  • 15
  • 28
2

Add an attribute to your form button called type. Specifically, something like:

type="button"

The reason is the default behavior of a button within a form is to act as a submit button. Submitting, results in the page being reloaded and thus the text field is cleared.

Ryan Dignard
  • 569
  • 1
  • 4
  • 15
1

That submits the form & reloads, to prevent it:

onclick="someFunction(); return false;">

Also you should avoid with().

Alex K.
  • 159,548
  • 29
  • 245
  • 267