在< input type =“number”中将值设置为货币/> [英] Set value to currency in <input type="number" />
问题描述
我试图将用户输入的数字格式化为使用javascript的货币。这适用于< input type =text/>
。然而,在< input type =number/>
我似乎无法将该值设置为包含非数字值的任何内容。以下小提琴显示我的问题
http:// jsfiddle .net / 2wEe6 / 72 /
有没有办法将值设置为 $ 125.00
?
我想使用< input type =number/>
用于数字输入的键盘。
最后,我制作了一个jQuery插件,它将格式化< ; input type =number/>
适合我。我还注意到在某些移动设备上, min
和 max
属性实际上并不妨碍您输入更低或更高的数字比指定的,所以插件也会说明这一点。以下是代码和示例:
.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。货币')。currencyInput();});
。货币{paddin g-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 =numberclass =currencymin =0.01
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
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.
解决方案 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" />
这篇关于在< input type =“number”中将值设置为货币/>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!