Reputation: 1174
I have created a fiddle to add two values and output the value. Fiddle is here:
http://jsfiddle.net/Q8KVC/2215/
When I enter values for input box(G7), value adds to G8 and shows the output. But when I delete the value in the input box using backspace, the value in the G8 doesn't change to the default value(0). I have tried with .on()
and .bind()
. But no luck. Please help me to find out the issue.
I am using the following event:
$("#g7").on("input keyup keydown keypress change blur", function() {});
Thanks.
Upvotes: 3
Views: 52
Reputation: 484
Edit: Disregard answer. I did not know input
was indeed valid.
Looking at the jQuery API Documentation, input
is not a valid event type. Perhaps seeing an unrecognized type caused it to drop the rest?
Upvotes: 0
Reputation: 4820
When #g7
is empty, parseFloat returns an empty string, so doing an addition operation on that results in NaN
. Also, you don't need all those events, in fact having all those events means that your funciton fires multiple times per keypress. The keyup
event should be sufficient, unless that input field is being externally updated, in which case you might use the change
event as well. Still, if you're doing external updates, I would preference forcing the update by doing something like $('#g7').trigger('keyup');
to trigger the event manually.
Try this code for your jQuery, it appears to work fine:
$(document).ready(function() {
$("#g7").on("keyup", function() {
var g6 =$('#g6').text();
var g7 =$('#g7').val() || 0;
var g8 =$('#g8').text();
var noCommasg6 = $('#g6').text().replace(/,/g, ''),
asANumber = +noCommasg6;
var sum=parseFloat(noCommasg6)+parseFloat(g7);
if (!isNaN(sum))
{
$("#g8").text(sum);
$('#g8').number( true, 2 );
}
});
});
Some other things to note:
$('#g8').number( true, 2 );
errors out with the message $(...).number is not a function
#g7
by changing the HTML input type="..."
to number
(instead of text
), so that alphabetic characters don't creep inUpvotes: 1
Reputation: 3103
When you delete all the characters in the input field, the value becomes an empty string.
var sum=parseFloat(noCommasg6)+parseFloat(g7);
Parse float on this line will evaluate to NaN
if (!isNaN(sum))
{
$("#g8").text(sum);
$('#g8').number( true, 2 );
}
Then you are checking and updatig g8 only if it is NaN.
You will need to include a case if g7 is null, then just set the default value to be zero
Upvotes: 1