Multiplying two inputs by JavaScript and displaying in a text box

I'm new to JavaScript, and I'm looking for some help that does a simple multiplication of two numbers and displays the result in another text box. I have been trying to get this job for many days to no avail :(

Here is the basic HTML along with JavaScript and a fiddle link here http://jsbin.com/egeKAXif/1/edit

What am I doing wrong?

The application I want to write will show at least 12 lines, how could I extend JavaScript / HTML for this? Should each input id be unique?

Any help is appreciated :)

<table width="80%" border="0"> <tr> <th>Box 1</th> <th>Box 2</th> <th>Result</th> </tr> <tr> <td><input id="box1" type="text" /></td> <td><input id="box2" type="text" onchange="calculate()" /></td> <td><input id="result" /></td> </tr> </table> <script> function calculate() { var myBox1 = document.getElementById('box1').value; var myBox2 = document.getElementById('box2').value; var result = document.getElementById('result'); var myResult = box1 * box2; result.innerHTML = myResult; } </script> 
+8
source share
2 answers

The first thing you need to change is a line with multiplication. It should be: var myResult = myBox1 * myBox2;

You should not use innerHTML with input fields - use a value.

In addition to this, the onchange event fires only when the input loses focus. You might want to use the oninput event.

Take a look at a working example: http://jsbin.com/OJOlARe/1/edit

+11
source
 <table width="80%" border="0"> <tr> <th>Box 1</th> <th>Box 2</th> <th>Result</th> </tr> <tr> <td><input id="box1" type="text" oninput="calculate();" /></td> <td><input id="box2" type="text" oninput="calculate();" /></td> <td><input id="result" /></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> <script> function calculate() { var myBox1 = document.getElementById('box1').value; var myBox2 = document.getElementById('box2').value; var result = document.getElementById('result'); var myResult = myBox1 * myBox2; document.getElementById('result').value = myResult; } </script> 

You cannot directly use result.innerHTML = myResult; for javascript variable. First you need to read the html dom element document.getElementById('result') , then call the value property for input fields or innerHTML for div, span elements.

+2
source

All Articles