Search code examples
jquerydecimal-point

Decimal places - jQuery


To place decimal plases in a text box I have use jquery.number plugin.

 $("#" + crisisCapId).number(true, 2);

After adding this plugin, if someone enter 0 i want to clear text box (" ").

 if (crisisCapValue == 0) {
      $("#" + crisisCapId).val(' ');
    }

But it is not working. How can we remove this plugin.

Full Code

 $("#" + crisisCapId).blur(function () {
        var crisisCapValue = $("#" + crisisCapId).val();

        if (crisisCapValue > 0) {
            $("#" + crisisCapId).number(true, 2);


        } else {

            $("#" + crisisCapId).val('');
        }

    });

Solution

  • This is happening because $("#" + crisisCapId).val() is a string, and therefore can't be evaluated against a number. You need to parse the input value as a number before your conditional:

    $('#' + crisisCapId).blur(function () {
    
        var $this = $(this),
            crisisCapValue = parseFloat($this).val());
    
        if (crisisCapValue > 0) {
            $this.val(crisisCapValue.toFixed(2));
        } else {
            $this.val('');
        }
    
    });
    

    Fiddle here: http://jsfiddle.net/jwmfuLLr/1/