How to prevent keypress two digits after a decimal number?

后端 未结 5 2010
花落未央
花落未央 2020-12-31 10:06

I have got a task to prevent keypress two digits after a decimal number. My jquery file is

$(function(){ 
    $(\'#name\').bind(\'paste\', function(){
             


        
5条回答
  •  孤独总比滥情好
    2020-12-31 10:35

    This might be helpful to some. I mixed the answers of this guy, @Tats_innit from https://stackoverflow.com/a/10514166/5382523 and @Rick Calder above.

    EDIT also from this guy, isJustMe from https://stackoverflow.com/a/17289322 for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.

    HTML

    
    

    JAVASCRIPT (JQUERY)

    $('.price').keypress(function(event) {
    
              if(event.which < 46 || event.which > 59) {
                  event.preventDefault();
              } // prevent if not number/dot
    
              if(event.which == 46 && $(this).val().indexOf('.') != -1) {
                  event.preventDefault();
              } // prevent if already dot
    
              var number = ($(this).val().split('.'));
              if (number[1].length > 2)
              {
               var price = parseFloat($("#txt_prod_price").val()) || 0;
               $("#txt_prod_price").val(price.toFixed(2));  
              }
    
          });
    

    the "price" is pre-defined.

    Note: still have buggy inputs but still kickin'. (y)

    More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

提交回复
热议问题