i would like to output a calculation of two input fields into a third, while it is typed in (keyup, i think?). The following is just a visual example, cause I don't know how to do it better:
<input type="text" class="form-control text-center" id="n1"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="n2"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="sum-out"
maxlength="2" readonly>
$(document).ready(function() {
var n1 = $("#n1").val();
var n2 = $("#n2").val();
var sum = ((n1 + n2) / 10) * 2;
sum = document.getElementById('sum-out')
return sum;
});
pls help...
You need to have the calculation performed when something "triggers" it, not as soon as the page is ready because the user hasn't had a chance to input any data yet. Adding a button that allows the user to tell the program that they are ready for the calculation to be performed is the simplest thing.
By the way, your calculation doesn't actually get the "sum" of the two inputs. You may want to reconsider your variable and element names.
$(document).ready(function() {
// You can't calculate the answer as soon as the page is ready.
// You need to wait until the user has done something that triggers
// the calculation. Here, it will happen as the user types into either
// of the first two inputs
$("#n1, #n2").on("input", calc);
// And also when the button is clicked
$("#calc").on("click", calc)
function calc(){
var n1 = $("#n1").val();
var n2 = $("#n2").val();
$('#result').val(((n1 + n2) / 10) * 2);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control text-center" id="n1"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="n2"
maxlength="2" placeholder="1-20">
<input type="text" class="form-control text-center" id="result"
maxlength="2" readonly>
<button type="button" id="calc">Calculate</button>