Skip to content Skip to sidebar Skip to footer

Calculating Form Field Input Value From Other Values With Onfocus

First time caller, long time listener.. I am attempting to have two user filled input fields on a php form be calculated to determine the value of another input field before the fo

Solution 1:

The input event will fire value change

https://developer.mozilla.org/en-US/docs/Web/Events/input

function PGCollectedCalc() {
    var num1 = document.getElementById('WG_Collected').value;
    var num2 = document.getElementById('Proof').value;
    var PG_Collected = parseFloat(num1) * parseFloat(num2)/100;
    document.getElementById('PG_Collected').innerHTML = PG_Collected.toFixed(2);
}

document.getElementById("WG_Collected").addEventListener("input", PGCollectedCalc, true);
document.getElementById("Proof").addEventListener("input", PGCollectedCalc, true);

The reason for input is that change will only fire off once you've removed focus from the inputs. http://jsfiddle.net/1wrnL3jp/4/ vs http://jsfiddle.net/1wrnL3jp/5/


Solution 2:

http://jsfiddle.net/7mwge85c/

HTML

<ul class="form-section">
 <li class="form-line" >
  <label for="WG_Collected">WG Collected</label>
  <div>
  <input type="number" id="WG_Collected" name="WG_Collected" value="15.0" min="0" step="0.1" required>
  </div>
 </li>
 <li class="form-line" >
  <label for="Proof">Proof</label>
   <div>
   <input type="number" id="Proof" name="Proof" Value="79.4" min="0" step="0.1" required>
   </div>
 </li>
 <li class="form-line" >
  <label for="PG_Collected">PG Collected</label>
   <div>
   <textarea type="number" id="PG_Collected" name="PG_Collected"></textarea>
   </div>
  <input type="button" value="Calculate PG" id="submitButton" />
 </li>
</ul>

Script working with keyup or onfocus(focus)

var button = document.getElementById("submitButton");
var inputOne = document.getElementById("WG_Collected");
var inputTwo = document.getElementById("Proof");

//keyup if you press any key
inputOne.addEventListener("keyup", function() {
    calcPG();
}, true);
inputTwo.addEventListener("keyup", function() {
    calcPG();
}, true);

//if some of the inputs get focus
inputOne.addEventListener("focus", function() {
    calcPG();
}, true);
inputTwo.addEventListener("focus", function() {
    calcPG();
}, true);

//your button click
button.addEventListener("click", function() {
    calcPG();
 }, true);

function calcPG (){
    var num1 = document.getElementById('WG_Collected').value;
    var num2 = document.getElementById('Proof').value;
    var PG_Collected = parseFloat(num1) * parseFloat(num2)/100;
    document.getElementById('PG_Collected').innerHTML = PG_Collected.toFixed(2);
}

Post a Comment for "Calculating Form Field Input Value From Other Values With Onfocus"