Reputation: 1015
There are two input fields total_amount
& delivery_charge
.
total_amount
field already have a value, now I want that when I input some value into delivery_charge
field that will change the total_amount
field's value.
Suppose total_amount
field's value is 200
.
Now I input 20
into delivery_charge
field and that will effect the total_amount
field and the value will be 220
.
For any type of changes of delivery_charge
field it will change the value of total_amount
field.
But for myself it will not change perfectly.
Suppose total_amount
is 200
when input delivery_charge
= 2
total_amount
= 202
when input delivery_charge
= 20
total_amount
= 2020
Here is my code detail
html
<h4>Grand Total : <input type="number" id="total_amount" readonly class="form-control total_amount" value="0.00"></h4>
<input type="text" name="delivery_charge" id="delivery_charge" class="form-control">
js
$('#delivery_charge').keyup(function(event) {
var total_amount = $('.total_amount').val();
var delivery_charge = $(this).val();
var grand_total_amount = total_amount + delivery_charge;
$('.total_amount').val(grand_total_amount);
});
Anybody help please? Thanks in advance.
Upvotes: 0
Views: 3495
Reputation: 893
You could try this solution.
total_amount
so that you could have the original value when we update it on delivery changes.parseInt()
to make sure the value you got is not a string.const total_amount = parseInt($('.total_amount').val());
$('#delivery_charge').keyup(function() {
$('.total_amount').val(total_amount + parseInt($(this).val() || 0));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Grand Total :
<input type="number" id="total_amount" readonly class="form-control total_amount" value="200"></h4>
<input type="number" name="delivery_charge" id="delivery_charge" class="form-control">
Upvotes: 4
Reputation: 58
To make sure you are dealing with numbers, use parseInt() (or parseLong() if you are dealing with huge numbers) as following
$('#delivery_charge').keyup(function(event) {
var total_amount = parseInt($('.total_amount').val());
var delivery_charge = parseInt($(this).val());
var grand_total_amount = total_amount + delivery_charge;
$('.total_amount').val(grand_total_amount);
});
Upvotes: 0