Zendie Zendie -4 years ago 91
jQuery Question

Jquery issue with on()

I have created a fiddle to add two values and output the value. Fiddle is here:


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

. 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() {});


Answer Source

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').number( true, 2 );

Some other things to note:

  • $('#g8').number( true, 2 ); errors out with the message $(...).number is not a function
  • You might want to restrict the values that can go in #g7 by changing the HTML input type="..." to number (instead of text), so that alphabetic characters don't creep in
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download