Home > database >  Adding space every three digits on input with JS
Adding space every three digits on input with JS

Time:09-29

I am building a 'calculator' on my site, and I would like the input numbers to be more readable by adding a space after every three digits. So, as someone is entering "1234567", I would like it to display as "1 234 567". I believe that I need to add another line of js for the id="amount"(html) var=amount (js), but I just don't know what that might look like... Bonus would be to have the outputs have a dollar sign ($) and separated by commas... Thank you in advance!

function calculate() {
   //Look up the input and output elements in the document
  var amount = document.getElementById("amount");
  var apr = document.getElementById("apr");
  var years = document.getElementById("years");
  var payment = document.getElementById("payment");
  var total = document.getElementById("total");
  var totalinterest = document.getElementById("totalinterest");
  
  // Get the user's input from the input elements.
  // Convert interest from a percentage to a decimal, and convert from
  // an annual rate to a monthly rate. Convert payment period in years
  // to the number of monthly payments.
  var principal = parseFloat(amount.value);
  var interest = parseFloat(apr.value) / 100 / 12;
  var payments = parseFloat(years.value);

  // compute the monthly payment figure
  var x = Math.pow(1   interest, payments); //Math.pow computes powers
  var monthly = (principal*x*interest)/(x-1);
  
  // If the result is a finite number, the user's input was good and
  // we have meaningful results to display
  if (isFinite(monthly)){
    // Fill in the output fields, rounding to 2 decimal places
    payment.innerHTML = monthly.toFixed(2);
    total.innerHTML = (monthly * payments).toFixed(2);
    totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2);
  }
  
  else {
  // Result was Not-a-Number or infinite, which means the input was
  // incomplete or invalid. Clear any previously displayed output.
  payment.innerHTML = ""; 
  // Erase the content of these elements
  total.innerHTML = ""
  totalinterest.innerHTML = "";
  }
}
<table class="table-bor">
 <tr><th class="title-borrow"></th>
 <td></td></tr>
 <tr><td class="calc-input">Amount of the loan ($):</td>
 <td><input id="amount" placeholder="$300 - $2,500" onchange="calculate();"></td>. 
 </tr>
 <tr><td class="calc-input">Annual interest (%):</td>
 <td><input id="apr" placeholder="6.50% - 10.00%" onchange="calculate();"></td></tr>
 <tr><td class="calc-input">Repayment period (years):</td>
 <td><input id="years" placeholder="1 - 18 months" onchange="calculate();"> 
 Months</td>
 <tr><th class="calc-input">Approximate Payments:</th>
 <td><button onclick="calculate();">Calculate</button></td></tr>
 <tr><td class="calc-input">Monthly payment:</td>
 <td>$<span class="output" id="payment"></span></td></tr>
 <tr><td class="calc-input">Total payment:</td>
 <td>$<span class="output" id="total"></span></td></tr>
 <tr><td class="calc-input">Total interest:</td>
 <td>$<span class="output" id="totalinterest"></span></td></tr>
</table>

CodePudding user response:

You can incorporate the space addition into your function calculate(). I've removed all the extraneous code and have included only the section needed to add spaces.

Note that you can apply this to the same calculate() function used by your three inputs because it now takes the element that is changed as a parameter.

When performing calculations with these "spaced" values, you'll need to remove spaces as I've done in the first line of the JavaScript function.

function calculate(element) {
    // get current value without any spaces
    contents = element.value.replace(/\s/g, '');

    // variable for storing replacement value that has spaces
    replacement = '';

    // loop through each character of the current value and add a space every three
    for (var i = 0; i < contents.length; i  ) {
        if (i % 3 == 0 && replacement.length > 0) {
            replacement = ' '   replacement;
        }
        replacement = contents.substring(contents.length - i, contents.length - i - 1)   replacement;
    }
    
    // replace the input value
    element.value = replacement;
}
<tr><td class="calc-input">Amount of the loan ($):</td>
<td><input id="amount" placeholder="$300 - $2,500" onchange="calculate(this);"></td>. 
</tr>
<tr><td class="calc-input">Annual interest (%):</td>
<td><input id="apr" placeholder="6.50% - 10.00%" onchange="calculate(this);"></td></tr>
<tr><td class="calc-input">Repayment period (years):</td>
<td><input id="years" placeholder="1 - 18 months" onchange="calculate(this);"> 
Months</td>

CodePudding user response:

On each of your inputs, you should add an Event listener for each input, listening for the input of the user:

let input = document.getElementById('amount')
input.addEventListener('input',(value)=>{
// ...
})

Then as the user types each character is considered a new input. Create a variable to count each time the input event is fired, and every 3 insert your space.

let input = document.getElementById('amount')
let count = 0;
input.addEventListener('input',(value)=>{
   count  
   if(count===3){
    input.value = input.value " "
    count = 0;
   }
})

Just remember when you do your calculations you'll need to remove the space to read the numbers correctly. Hope this works for you!

  • Related