Set value to currency in <input type=“number” />

后端 未结 5 2058
逝去的感伤
逝去的感伤 2020-12-01 01:35

I am trying to format a number input by the user into currency using javascript. This works fine on . However, on

5条回答
  •  星月不相逢
    2020-12-01 02:27

    In the end I made a jQuery plugin that will format the appropriately for me. I also noticed on some mobile devices the min and max attributes don't actually prevent you from entering lower or higher numbers than specified, so the plugin will account for that too. Below is the code and an example:

    (function($) {
      $.fn.currencyInput = function() {
        this.each(function() {
          var wrapper = $("
    "); $(this).wrap(wrapper); $(this).before("$"); $(this).change(function() { var min = parseFloat($(this).attr("min")); var max = parseFloat($(this).attr("max")); var value = this.valueAsNumber; if(value < min) value = min; else if(value > max) value = max; $(this).val(value.toFixed(2)); }); }); }; })(jQuery); $(document).ready(function() { $('input.currency').currencyInput(); });
    .currency {
      padding-left:12px;
    }
    
    .currency-symbol {
      position:absolute;
      padding: 2px 5px;
    }
    
    

提交回复
热议问题