问题
I have this script that was maked by another memeber of stackoverflow but I need to put a comma separator for thousands numbers.
How I can do that?
(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="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />
回答1:
- You can't put commas on a "number" input, so change it to "text".
- Since you can't use "toLocaleString" and toFixed together, a different solution is needed:
(function($) {
$.fn.currencyInput = function() {
this.each(function() {
var wrapper = $("<div class='currency-input' />");
$(this).wrap(wrapper);
$(this).before("<span class='currency-symbol'>$</span>");
$(this).val(parseFloat($(this).val()).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2}));
$(this).change(function() {
var min = parseFloat($(this).attr("min"));
var max = parseFloat($(this).attr("max"));
var value = parseFloat($(this).val().replace(/,/g, ''));
if(value < min)
value = min;
else if(value > max)
value = max;
$(this).val(value.toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2}));
});
});
};
})(jQuery);
$(document).ready(function() {
$('input.currency').currencyInput();
});
.currency {
padding-left:12px;
}
.currency-symbol {
position:absolute;
padding: 2px 5px;
}
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<input type="text" class="currency" min="0.01" max="2500.00" value="1125.00" />
来源:https://stackoverflow.com/questions/40093527/add-thousand-comma-separators-to-input-type-number