jQuery onchange event not firing when input value changed by another function is zero or blank
The following code calculates the specified percentage of a number in two textboxes. And displays the sum of those percentages in an output tag. It all works fine except if the percentage of any number is 0. Example:
Textbox1: 4% of 200 = 8
Textbox1: 15% of 300 = 45
Output tag = 53
But if I change the 4 to 0: 0
% of 200 = 0 displays correctly. But the output tag does not change from 53 to 45. This happens only if % textbox is changed to 0. If I change it to say 11 as: 11
% of 200 = 22, the output tag would correctly change to 67 (22+45).
RESOLVED
I finally figured out what the problem was. The input boxes at another place were first validating the input as shown below. Since 0 or blank would not pass the following test, the function PercentOfTwoNumbers was never called for these two values. Thank your for those who may have tried to help.
var validateInput = function (val) {
if (!isNaN(val) && val.length != 0 && parseFloat(val).toFixed(0) != 0) {
return true;
}
return false;
};
EDIT
1. I've corrected the typos pointed out by Dave in his response.
<input type="text" class="class1" value="" />% of <input type="text" class="class11" value="" /> = <input type="text" class="class111 classA" value="" />
<input type="text" class="class2" value="" />% of <input type="text" class="class22" value="" /> = <input type="text" class="class222 classA" value="" />
<input type="text" class="classTotal" value="" />
- $(document).ready(function() {
- var PercentOfTwoNumbers = function(selector1, selector2, outputdiv) {
- $(selector1 + ',' + selector2).change(function() {
- var prcnt = 0;
- var v1 = parseInt($(selector1).val(), 10);
- var v2 = parseInt($(selector2).val(), 10);
- if (!isNaN(v1) && !isNaN(v2)) {
- prcnt = v1 * v2 / 100;
- $(outputdiv).val(prcnt).change();
- }
- else {
- $(outputdiv).val(0);
- }
- });
- };
- $('.classA').on('change', function() {
- var total = 0;
- $('.classA').each(function(index) {
- total += parseFloat($(this).val() ? $(this).val() : 0);
- });
- $('.classTotal').val(total.toFixed(2)).change();
- });
- PercentOfTwoNumbers('.class1', '.class11', '.class111');
- PercentOfTwoNumbers('.class2', '.class22', '.class222');
- });
-