Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML display result in text (input) field?

I have a simple HTML form, with 3 input field, when you hit = button, it suppose to add 2 numbers that you typed in the first 2 input fields and display result in 3rd filed. Is it possible to do that? (I need result in a box (or table) or some thing rather than in plain text). I try the following but doesn't work (it does nothing), can somebody help me?

<HTML>
      <HEAD>
        <TITLE>Sum</TITLE>

        <script type="text/javascript">
          function sum()
          {
             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').innerHTML = sum;
          }
        </script>
      </HEAD>

      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""> + 
          <INPUT TYPE="text" NAME="number2" VALUE="">
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()">
          <INPUT TYPE="text" ID="add" NAME="result" VALUE="">
        </FORM>

      </BODY>
</HTML>
like image 611
Ronaldinho Learn Coding Avatar asked Jun 14 '12 20:06

Ronaldinho Learn Coding


People also ask

How do I get the value of text input field using JavaScript?

We can get the value of the text input field using various methods in JavaScript. There is a text value property that can set and return the value of the value attribute of a text field. Also, we can use the jquery val() method inside the script to get or set the value of the text input field.


1 Answers

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;
like image 197
Nathan Wall Avatar answered Sep 28 '22 15:09

Nathan Wall