I'm very new to javascript and created a simple calculator that calculates cost based on quantity with +/- buttons controlling the quantity input. It works how I want it to, but I can't figure out how to format the cost result with thousand comma separators once the cost estimate exceeds $1000 with 2 items.
In other words, when you increase quantity to 2, how do you get it to print as $1,400 instead of $1400?
Here's what I tried below
$(document).ready(function() {
$(".calculator").on("input", ".quantity", function() {
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("$" + price * quantity);
})
var $buttonPlus = $('.increase-btn');
var $buttonMin = $('.decrease-btn');
var $quantity = $('.quantity');
/*For plus and minus buttons*/
$buttonPlus.click(function() {
$quantity.val(parseInt($quantity.val()) + 1).trigger('input');
});
$buttonMin.click(function() {
$quantity.val(Math.max(parseInt($quantity.val()) - 1, 0)).trigger('input');
});
})
/*For number formatting*/
$(document).on('input', '.total', function() {
var x = $(this).val();
$(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});
.checkout {
height: 300px;
width: 400px;
margin: 20px auto;
}
input {
text-align: center;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="calculator">
<h1 class="title">Estimate Cost</h1>
<p class="price" data-price="700">$700 per item</p>
<p class="description">Quantity:</p>
<button type="button" class="decrease-btn">-</button>
<input type="text" class="quantity" value="1">
<button type="button" class="increase-btn">+</button>
<p class="total">Total: <span id="total">$700</span></p>
</div>