在中将值设置为货币(Set value to currency in )

编程入门 行业动态 更新时间:2024-10-27 04:24:13
中将值设置为货币(Set value to currency in )

我正尝试将用户输入的数字格式化为使用javascript的货币。 这适用于<input type="text" /> 。 但是,在<input type="number" />我似乎无法将该值设置为包含非数字值的任何内容。 下面的小提琴显示我的问题

http://jsfiddle.net/2wEe6/72/

无论如何,我可以将价值设置$125.00 ?

我想使用<input type="number" />以便移动设备知道为数字输入提供一个键盘。

I am trying to format a number input by the user into currency using javascript. This works fine on <input type="text" />. However, on <input type="number" /> I cannot seem to be able to set the value to anything that contains non-numeric values. The following fiddle shows my problem

http://jsfiddle.net/2wEe6/72/

Is there anyway for me to set the value to something like $125.00?

I want to use <input type="number" /> so mobile devices know to bring up a keyboard for number input.

最满意答案

将< step="0.01"添加到<input type="number" />参数中:

<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />

演示: http : //jsfiddle.net/uzbjve2u/

但美元符号必须留在文本框之外......每个非数字或分隔符字符将自动裁剪。

否则,您可以使用经典的文本框, 如此处所述 。

In the end I made a jQuery plugin that will format the <input type="number" /> 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 = $("<div class='currency-input' />");
      $(this).wrap(wrapper);
      $(this).before("<span class='currency-symbol'>$</span>");
      $(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;
} 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" /> 
  
 

更多推荐

number,type,数字,<input,电脑培训,计算机培训,IT培训"/> <meta name="desc

本文发布于:2023-07-22 20:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1223294.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   中将   货币   currency   Set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!