How to add oninput outside of the input field

Hi,

I found this function http://jsbin.com/sosarudiju/edit?html,js,output but I can’t add the oninput=“calculate()” part to the input fields. How could I add the oninput=“calculate()” to the function?

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  
<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>
<script>
	function calculate() {
		var myBox1 = document.getElementById('box1').value;	
		var myBox2 = document.getElementById('box2').value;
		var result = document.getElementById('result');	
		var myResult = myBox1 * myBox2;
		result.value = myResult;
      
		
	}</script>

Thank you

Your code works for me, but you can do it instead using addEventListener with:

document.querySelector("#box1").addEventListener('input', calculate, true);
document.querySelector("#box2").addEventListener('input', calculate, true);

I can’t get it to work.

  <tr>
    <td><input id="box1" type="text" /></td>
    <td><input id="box2" type="text" /></td>
    <td><input id="result" /></td>
  </tr>
  <tr>
<script>
	function calculate() {
		var myBox1 = document.querySelector("#box1").addEventListener('input', calculate, true);
		var myBox2 = document.querySelector("#box2").addEventListener('input', calculate, true);
		var result = document.getElementById('result');	
		var myResult = myBox1 * myBox2;
		result.value = myResult;
      
		
	}</script>

Please revert the calculate function back to how you had it before you made the changes to it.

Place the event listener lines after the calculate function instead.

You mean something like this:

  <tr>
    <td><input id="box1" type="text" /></td>
    <td><input id="box2" type="text" /></td>
    <td><input id="result" /></td>
  </tr>
  <tr>
<script>
	function calculate() {
		document.querySelector("#box1").addEventListener('input', calculate, true);
		document.querySelector("#box2").addEventListener('input', calculate, true);	
		var myBox1 = document.getElementById('box1').value;	
		var myBox2 = document.getElementById('box2').value;
		var result = document.getElementById('result');	
		var myResult = myBox1 * myBox2;
		result.value = myResult;
      
		
	}</script>

I hope not because it doesn’t work!

No I don’t. I mean exactly as I said before. I’ll repeat it again. Please read carefully.

Please revert the calculate function back to how you had it before you made the changes to it.
Place the event listener lines after the calculate function instead.

Oh okay, after! not in the middle.

It works now. thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.