Cj_Cipher
Cj_Cipher

Reputation: 9

Text display and gone again in JavaScript

I don't know what is happening. I'm inputting value for the operation to solve but when it displays the result it displays but in a brief time only.

function add(){
        var num1 = document.getElementById('fnum').value;
        var num2 = document.getElementById('snum').value;
        var ans = parseFloat(num1) + parseFloat(num2);

        document.getElementById('res').value = ans;
    }
<form>
  1st Number:<input type="text" id="fnum" name="Num1" /><br>
  2nd Number:<input type="text" id="snum" name="Num2" /><br><br>
  <input type="submit" value="Add" id="button1" name="button" onclick="add()"/>
  The result is:<input type="text" id="res" name="res" readonly="true" /><br>
</form>

Upvotes: 1

Views: 76

Answers (2)

Knelis
Knelis

Reputation: 7149

Because you are using the <form> tag with a <button type="submit">, the form is submitted.

So what's happening is that your onclick event is handled, but when that's done, the form is still submitted. You have multiple ways of fixing this:

  • Don't use <form>
  • Change the <button> type to button
  • Handle the form submit in JavaScript
  • Cancel the click event

Here's a working version without a <form> tag and <button type="button">:

function add() {
    var num1 = document.getElementById('fnum').value;
    var num2 = document.getElementById('snum').value;
    var ans = parseFloat(num1) + parseFloat(num2);

    document.getElementById('res').value = ans;
}
  1st Number:<input type="text" id="fnum" name="Num1" /><br>
  2nd Number:<input type="text" id="snum" name="Num2" /><br><br>
  <input type="button" value="Add" id="button1" name="button" onclick="add()" />
  The result is:<input type="text" id="res" name="res" readonly="true" /><br>

Upvotes: 2

fachrilinggo
fachrilinggo

Reputation: 283

it's because your button is a submit component, change :

<input type="submit" value="Add" id="button1" name="button" onclick="add()"/>

to

<button type="button" value="Add" id="button1" name="button" onclick="add()">add</button>

a submit component used to submit your form so you'll need a valid action in your form for that. or you can use onsubmit event for your form to prevent default form action

Upvotes: 0

Related Questions