saadi123
saadi123

Reputation: 614

Javascript forms Value disappear

First the code:

    <html>
    <head></head>
    <body>
     <script>
        function calc_form(first, second) {
            x = document.getElementById("calc");
            first = document.forms["calc"].elements["first"].value;
            second = document.forms["calc"].elements["second"].value;
            third =  first*second;
            document.forms["calc"].elements["result"].value = third;
            document.getElementById("result1").innerHTML = third;
        }
    </script>
<form name = "calc">
    <input type = "text" name="first">
    <input type="text" name="second">
    <input type="submit" onclick = "calc_form()"><br>
    <input type="text" id="result">
</form>
<p id="result1"></p>
 </body>
</html>

I know that this is a useless and very poor code but I want to know that why does the values that I enter in the input box disappear right after I click the "Submit" button.

Similarly, the result in the third input box appears only for a moment and then disappears. Why is this happening?

Upvotes: 0

Views: 4060

Answers (1)

sna19
sna19

Reputation: 404

When one click on html submit button, the form values are collected and server request is generated. Depending on request type defined (POST or GET), the data are sent to the server in URL or form format. After request the page is refreshed because the client html code is rendered again.

You can build the logic reading the values after server side response received results to client. However, I guess you need in your code to to prevent sending data to the server side each time you click on the button and to make calculations on the client only. There're two ways you could do that:

  1. change the type of the button from "submit" to "button".
  2. in the oncick event as well as at the end of the function "return false". It prevents from the submit action and sending submit request to server.

    <input type="submit" onclick="return calc_form()">

then:

function calc_form(first, second) {
        ...
        return false;
        ...
    }

Upvotes: 2

Related Questions