I'm trying to add a thousands separator for the .htm(price * num)
result by adding .digits();
to the var sub
. How do I get the thousands seperator to work on the result of the var sub
? Since they are not val
do I need to convert the result into a number before adding the digits();
function?
$(document).ready(function() {
$.fn.digits = function() {
return this.each(function() {
$(this).val(
$(this)
.val()
.replace(/(\d)(?=(\d\d\d) (?!\d))/g, "$1,")
);
});
};
var total = $(".slider__total").html();
var sold = $(".sold").html();
var available = total - sold;
var price = $(".cost").html();
var num = $("#num").html();
$(".item__available").html(available);
var sub = $("#slider_subtotal")
.html(price * num)
.digits();
$(".qty").attr({
max: available
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sold<span >3</span>total<span >10</span>available<span ></span><input type="range" min="1" value="1" name='quantity' oninput="num.value = this.value"><output id="num">0</output>unit:
$
<span >500</span>subtotal: $<span id="slider_subtotal">0</span>
CodePudding user response:
You could use the built-in Number.prototype.toLocaleString()
method instead:
(1234567.567).toLocaleString('en-US') // 1,234,567.567
Or - if you prefer - you can also keep it "local" to the current user by omitting the first argument: (1234567.567).toLocaleString()
will refer to the browsers regional settings and will return a suitable local number string.
$(document).ready(function() {
var total = $(".slider__total").text();
var sold = $(".sold").text();
var available = total - sold;
var price = $(".cost").text();
$(".item__available").html(available);
$(".qty").attr({max: available})
.on("input",function(){
$("#slider_subtotal").text((price * this.value).toLocaleString("en-US",{style:'currency', currency:'USD'}));
$("#num").text(this.value)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
sold<span >37</span>
total<span >103</span>
available<span ></span>
<input type="range" min="1" value="1" name='quantity'>
<output id="num">0</output>
unit:$<span >123.4</span>
subtotal: <span id="slider_subtotal">$0</span>