Reputation: 135
I need to Multiply two user Input Fields and show the results in the third field. The Result field must change when either of the User Input fields are changed.
<input type="number" name="rate" id="rate" />
<input type="number" name="box" id="box" />
The result should be in a third field which changes when either of the two above fields is changed. This totally depends on the user input
<input type="number" name="amount" id="amount" readonly />
I need to do this Multiplication with Jquery.
Thanks in advance
Upvotes: 0
Views: 12923
Reputation: 331
<script type="text/javascript">
$("#txtOne,#txtTwo").on("change keyup", function(e){
var txtOne = parseFloat($("#txtOne").val());
var txtTwo = parseFloat($("#txtTwo").val());
var result = txtOne * txtTwo ;
if (!isNaN(result)) {
$("#txtAmount").val(result);
}
});
</script>
Upvotes: 0
Reputation: 445
Here is my 2 cents on the above scenario - http://jsfiddle.net/ak9ejpne/3/
My aim was to keep the code thin & clean and with some MVC flavor.
function Operand(a,b){
this.a = parseInt(a);
this.b = b;
this.c = (this.a)*(this.b);
this.set = function(key,edit){
this[key] = edit;
this.c = (this.a)*(this.b);
};
return this;
}
Do let me know if it is a useful approach for you :)
Upvotes: 0
Reputation: 336
Try this : bind input
event listener on
rate and box input box and inside it multiply the values to put it in amount input.
The input
event only fires when the value of the input has changed whereas change
only fires once the field has lost focus. input fires immediately
$('#rate, #box').on('input',function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="number" name="rate" id="rate" value=""/>
<input type="number" name="box" id="box" value=""/>
<input type="number" name="amount" id="amount" readonly />
Upvotes: 1
Reputation: 28513
Try this : bind change
event listener for rate
and box
input box and inside it multiply the values to put it in amount
input.
$('#rate, #box').change(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
You can use keyup
event to calculate amount
as soon as you enter other fields
$('#rate, #box').keyup(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
Upvotes: 6