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
functionPGCollectedCalc() {
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:
HTML
<ul class="form-section">
<liclass="form-line" ><labelfor="WG_Collected">WG Collected</label><div><inputtype="number"id="WG_Collected"name="WG_Collected"value="15.0"min="0"step="0.1"required></div></li><liclass="form-line" ><labelfor="Proof">Proof</label><div><inputtype="number"id="Proof"name="Proof"Value="79.4"min="0"step="0.1"required></div></li><liclass="form-line" ><labelfor="PG_Collected">PG Collected</label><div><textareatype="number"id="PG_Collected"name="PG_Collected"></textarea></div><inputtype="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);
functioncalcPG (){
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"