Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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;

Solution 2:

<HTML><HEAD><TITLE>Sum</TITLE><scripttype="text/javascript">functionsum()
          {

             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script></HEAD><BODY><FORMNAME="myform"><INPUTTYPE="text"NAME="number1"VALUE=""/> + 
          <INPUTTYPE="text"NAME="number2"VALUE=""/><INPUTTYPE="button"NAME="button"Value="="onClick="sum()"/><INPUTTYPE="text"ID="add"NAME="result"VALUE=""/></FORM></BODY></HTML>

This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags

Solution 3:

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Solution 4:

With .value and INPUT tag

<HTML><HEAD><TITLE>Sum</TITLE><scripttype="text/javascript">functionsum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script></HEAD><BODY><FORMNAME="myform"><INPUTTYPE="text"NAME="number1"VALUE=""/> + 
      <INPUTTYPE="text"NAME="number2"VALUE=""/><INPUTTYPE="button"NAME="button"Value="="onClick="sum()"/><INPUTTYPE="text"ID="add"NAME="result"VALUE=""/></FORM></BODY></HTML>

with innerHTML and DIV

<HTML><HEAD><TITLE>Sum</TITLE><scripttype="text/javascript">functionsum()
      {

         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><FORMNAME="myform"><INPUTTYPE="text"NAME="number1"VALUE=""/> + 
      <INPUTTYPE="text"NAME="number2"VALUE=""/><INPUTTYPE="button"NAME="button"Value="="onClick="sum()"/><DIVID="add"></DIV></FORM></BODY></HTML>

Post a Comment for "Html Display Result In Text (input) Field?"