Morgari Morgari - 29 days ago 12
Javascript Question

Separate numbers with comma n fields in my code

I have the following code. In the text input field how can I make it so that a comma is appropriately added to the number? For example, instead of it saying “1000” make it say “1,000”. Or as another example, if I inputted “1000000” make it say “1,000,000”. Unfortunately JS is not my strong side.
Thank you in advance!

function priceCalculation(a){
if(a <= 10000){
return 0.00099;
}else if(a >= 10001 && a <= 25000 ){
return 0.00095;
}else if(a >= 25001 && a <= 50000 ){
return 0.00089;
}else if(a >= 50001 && a <= 100000 ){
return 0.00075;
}else{
return 0.00075;
}
}

$('#likecount').keyup(function(){
var price = priceCalculation($(this).val());
console.log(price)
var total = $(this).val() * price;
$('#output').text(total.toFixed(2));
});



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="likecount" />
<p style="padding: 20px 0px; font-weight: bold; color: #222; ">Your Cost: <b><span> $</span><span id="output" style="color: #004f04;"></span></b></p>


Screenshot where I need the commas:
enter image description here

Answer

with the use of ECMAScript 6's number formatting (see here) you can do it like:

UPDATED SCRIPT :

function priceCalculation(a){
    if(a <= 10000){
        return 0.00099;
    }else if(a >= 10001 && a <= 25000 ){
        return 0.00095;
    }else if(a >= 25001 && a <= 50000 ){
        return 0.00089;
    }else if(a >= 50001 && a <= 100000 ){
        return 0.00075;
    }else{
        return 0.00075;
    }
}

// number format set to en-US e.g (from 1500 to 1,500)
var numFormat = new Intl.NumberFormat("en-US");

$('#likecount').keyup(function(e){
    // if a '.' is pressed
	if($(this).val().endsWith('.')) {
    	return;
    }

    // if input value is empty then assign '0' else the original value
    var inputVal = $(this).val() === ''?'0':$(this).val();
  
    // replace the ',' to '' so we won't get a NaN result
    // on arithmetic operations
    inputVal = parseFloat(inputVal.replace(/[$|,]/g, ''));
    var price = priceCalculation($(this).val());
    var total = inputVal * price;
    var formatted = numFormat.format(inputVal) // set format to input
    $(this).val(formatted); // display the formatted input back
    $('#output').text(numFormat.format(total)); // display the total price
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="likecount" />
        <p style="padding: 20px 0px; font-weight: bold; color: #222; ">Your Cost: <b><span> $</span><span id="output" style="color: #004f04;"></span></b></p>